Home > OS >  Coverting Float to String with comma without Rounding
Coverting Float to String with comma without Rounding

Time:07-02

I'm using this for adding commas into number.

val commaNumber = NumberFormat.getNumberInstance(Locale.US).format(floatValue)

floatValue is 8.1E-7 , but commaNumber shows just 0.

How to covert Float to String with comma without Rounding?

CodePudding user response:

For the US locale, the maximumFractionalDigits of the number format is 3, therefore, it will try to format 8.1e-7 with only 3 fractional digits, which makes it 0.000. Since the minimumFractionalDigits is also 0, it tries to remove all the unnecessary 0s, making the final result "0".

You should set maximumFractionalDigits to at least 7 if you want to precisely display the number 8.1e-7.

val numberFormat = NumberFormat.getNumberInstance(Locale.US)
numberFormat.maximumFractionDigits = 7
val commaNumber = numberFormat.format(floatValue)

As for the commas, that is already part of the US locale. It uses grouping, and , is its grouping separator. The commas will be inserted if they are needed.

  • Related