Search code examples
androidkotlinnumber-formatting

Currency NumberFormat change the `format` behaviour after calling `parse`


I create a numberFormat to not return strings with decimals like:

val numberFormat = NumberFormat.getCurrencyInstance().apply {
    minimumFractionDigits = 0
}

1. If I call format it returns fine

numberFormat.format(123) // "$123"

2. If I call parse with other value

numberFormat.parse("$333") // a number -> 333

3. And call format again with 123, the returned value contains the decimals! the format changed!.

numberFormat.format(123) // "$123.00"

Why? What can we do so it returns always with format without decimals like 1.?

I made a repo to reproduce it: https://github.com/danielgomezrico/test-numericformat-format-parse-error-sample.

It looks like it only fails on android not in java.

Take a look to MainActivity.kt


Solution

  • Never used NumberFormat so I am not sure why it acts like that... but one work around would be to make your numberFormat a class variable with a custom getter like so:

    val numberFormat: NumberFormat
        get() = NumberFormat.getCurrencyInstance().apply { maximumFractionDigits = 0 }
    

    and then when you access it this way, it will apply the maximumFractionDigits each time