Can't convert double to format string

Viewed 48

Suppose I has number

123456789

After format the result must be

123,456,789.00

Here snippet

private val decimalFormat = DecimalFormat("#,###.##")
 val resultSubTotalAmount = 12345678901 / 100
 val resultFormatSubTotalAmount = decimalFormat.format(resultSubTotalAmount)

And here result:

resultFormatSubTotalAmount = 123,456,789

But I need: 123,456,789.00

2 Answers

You can use the following

DecimalFormat("#,#,#.00")
  • This only works for numbers 1.000.000 < x < 1.000.000.000 (since we require two ,s with integers in between)
  • and rounds the double down (a floor).

Note: we can use single #s in the DecimalFormat because

the integer part is never discarded, no matter if the pattern is smaller than the number

If you want to round it down, you can always change the format:

DecimalFormat("#,###.00")
Related