Daniel Gomez Rico
Daniel Gomez Rico

Reputation: 15936

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

Upvotes: 2

Views: 106

Answers (1)

Quinn
Quinn

Reputation: 9434

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

Upvotes: 1

Related Questions