Kotlin float number with 2 decimals to string without precision loss

Viewed 8622

In Android-Kotlin I am getting float number from backend (for example num = 10000000.47) When I try to String.format it and add that number in my balanceTextview it shows it with exponent (something like 1.0E10).

I want to show number normally without exponent and with 2 decimals. (Without presicion loss!)

Tried to use DecimalFormat("#.##") but it didn't help me. Maybe I'm doing something wrong?

num = 10000000.47f
 val dec = DecimalFormat("#.##")
 var result = dec.format(num)

my result is: 10000000
It losts my decimal places
1 Answers

The issue is your number type. According to the documentation:

For variables initialized with fractional numbers, the compiler infers the Double type. To explicitly specify the Float type for a value, add the suffix f or F. If such a value contains more than 6-7 decimal digits, it will be rounded.

With an example that shows how information may get lost:

val pi = 3.14 // Double
val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float, actual value is 2.7182817

If the value is specified as Double instead of Float, i.e.

val num = 10000000.47

instead of

val num = 10000000.47f

then your approach works as expected, but could be shortened to:

"%.2f".format(num)

(note that the shorter version will also print "100" as "100.00" which is different from your approach but potentially still desired behaviour)

If you receive a Float from the backend then the information is already lost on your side. Otherwise you should be able to fix the issue by improved parsing.

Related