How to avoid auto rounding done by NumberFormat(Locale).format() method while formatting a value?

StackOverflow https://stackoverflow.com/questions/14104856

  •  13-12-2021
  •  | 
  •  

Okay so my problem is.. when I try to format a number into a currency string(e.g. 10.23 to $10.23), using format method of NumberFormat class, it automatically rounds off the value. And this is occurring specifically when I pass Japanese/Korean locale to NumberFormat's getCurrencyInstance() method. In case of US locale, things are working fine. Here is the snippet that will give a clear picture of the problem:

        NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.JAPAN);
        BigDecimal bd = new BigDecimal(123.456);
        String str = formatter.format(bd);
        JOptionPane.showMessageDialog(null, str); // Output is coming ¥123 instead of ¥123.456  

I am not sure if I am missing something or doing something illogical. If not then Is there a way to prevent this round off? Please help.

有帮助吗?

解决方案 2

Nambari is right. Take a look at this:

NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.JAPAN);
BigDecimal bd = new BigDecimal(123.456);
String str = nf.format(bd);
System.out.println("" + nf.getMaximumFractionDigits()); //prints out 0
System.out.println(str);

It seems like the default fraction digits for Japan is set to 0. When I do the same for Locale.US it apparently defaults to 2. Use Nambari's answer and setMaximumFractionDigits.

As to why, thanks to @Lee Meador for pointing it out in a comment, Japanese currencies do not use decimal places (aka the single yen is as far as you can go).

From a wikipedia article on the Japanese yen:

"Coins in denominations of less than 1 yen became invalid on December 31, 1953, following enforcement of the Small Currency Disposition and Fractional Rounding in Payments Act"

Since I'm too lazy to look up the Korean currency, I'm just going to assume they have a similar situation.

其他提示

It seems you need to set setMaximumFractionDigits for the NumberFormat

    NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.JAPAN);
    BigDecimal bd = new BigDecimal(123.456);  
    formatter.setMaximumFractionDigits(4); //Replace 4 with whatever value applicable for you.
    String str = formatter.format(bd);

output:

¥123.456
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top