javaandroidkotlindecimalformat

DecimalFormat behaves different if decimal ends with 5 digit


DecimalFormat is behaving differently on Android [Kotlin] vs. Kotlin scratch file in my Android Studio, if decimal digits end at 5.

For example; if I try to format 10.495 with 2 decimal places, Android shows 10.50 while Kotlin scratch file returns 10.49.

Please note that my Mac OSX has java 17 installed, so Kotlin file is running on Java 17. While build.gradle has been configured to use jvm 11. I tried to use Jvm 17 in build.gradle, but still the result was same.

Code:

fun formatNumber(num: Double): String {
    val df = DecimalFormat("0.00")
    df.roundingMode = HALF_EVEN
    return df.format(num)
}

Formatted Result on Android

Original Value Rounded off
23.805 23.80
15.985 15.98
10.495 10.50 <--
49.505 49.50 <--

Formatted Result on Kotlin Scratch File

Original Value Rounded off
23.805 23.80
15.985 15.98
10.495 10.49 <--
49.505 49.51 <--

Please note the difference in last two numbers. I want to understand why both have different results. I have tried different rounding modes, but none helps. Even iOS and web has results same as Kotlin scratch file. I came across this bug in JDK, but it has been marked resolved. Even using BigDecimal doesn't help. How can I make sure it rounds off correctly if last digit is 5 using existing language libs? Any direction is appreciated. Thanks.


Solution

  • THat's the rounding mode you specified. HALF_EVEN means an exact .5 rounds to the even number. Specify the rounding mode you prefer if you don't want that. HALF_UP may be what you want.