Why does an integer not format correctly (Kotlin/Java)?

Asked

Viewed 130 times

2

I use the Android Studio 3.4.2. I ran a test code that generates a very strange format. This excerpt was placed right after the beginning of the onCreate. And it’s a pure integer!

fmtFloat = DecimalFormat("#,###.##############")   
fmtFloat.setRoundingMode(RoundingMode.CEILING)
Log.d("myMess", fmtFloat.format("98765432".toDouble()))

The image of logCat is

LogCat

When I rotate this expression in the evaluation window, the same problem occurs:

Evaluate Window

However, when I run the SAME code as a desktop test on Android Studio, no error appears.

98.765.432

In the Kotlin Playground also works OK.

Because it happens in Android app and does not happen on Desktop? What’s the difference?

As it is a library Java, I tagged the Java in the question, in addition to Kotlin.

Debugging the app Android app, I circled in the expression evaluation window:

"98765432".toDouble()==98765432.0

Yes, it’s true, of course!

UPDATING
When using default rounding mode (HALF_EVEN) stop Decimal Format, the app starts to work normally on Android, accepting up to 14 digits (which I chose for security) before starting to display the number in exponential format. Thus follows the mystery ...

UPDATE 2
My number using rounding mode Ceiling in the variable format method Decimal Format is a Double, that has 64 bits with 53 bits for mantissa. It would thus be able to correctly store numbers up to 16 digits and my number has only 8 digits!

Java double

  • Maybe it’s a difference of locale. Which locale you get when you run Locale.getDefault() in these different environments?

  • Leonardo, here Pt-Br same. I can change the location programmatically and it doesn’t interfere. I’ve tried it.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.