简体   繁体   中英

How can I get NumberFormat to use a currency but with fractional cents/pennies?

I'd like to use NumberFormat to convert a Double to a String . I'm currently using a NumberFormat based on a currency locale but this rounds the Double to 2 decimal places. How could I get it to not round the currency so that it includes fractional pennies?

So if I have

val doubleFormatMoney = 1.032323135

val format = NumberFormat.getCurrencyInstance(Locale.US)

val stringFormatMoney = format.format(doubleFormatMoney)

Then we should have stringFormatMoney = $1.032323135 but instead I get stringFormatMoney = $1.03

The per-Locale currency format specification includes how many decimal places to use, since that varies by currency (some currencies use 3dp, for example the Jordanian Dinar). Therefore NumberFormat.getCurrencyInstance(Locale.US) includes rounding to 2dp by definition.

If you want to use the standard Double toString plus the Locale's currency symbol, you can do:

Currency.getInstance(Locale.US).getSymbol(Locale.US) + doubleFormatMoney

See How to get the currency symbol for particular country using locale?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM