Java - NumberValue to String without Currency sign

♀尐吖头ヾ 提交于 2020-05-15 10:08:06

问题


I am trying to format a NumberValue as a String in the current locale format.

For example, for Locale.Germany these would be the results I am trying to get:

1   -> 1,00
1.1 -> 1,10
0.1 -> 0,10

What I have tried:

String test1 = NumberFormat.getInstance().format(1.1);
// -> 1,1
String test2 = NumberFormat.getCurrencyInstance().format(1.1);
// -> 1,10 €

How could I get the same format as the second example, without the currency symbol? Or alternativly, how could I make sure the result from the first example always has the amount of decimals needed for the current locale?

Edit: Since there are some currencies that have 0,2 or 3 decimals, I don't think setting the decimals to a fixed amount will have the correct results.

Also, some currencies have their symbol in the front, and some in the back, so cutting off the last characters will probably not work either.

http://apps.cybersource.com/library/documentation/sbc/quickref/currencies.pdf


回答1:


java.util.Currency provides the necessary information. A reasonable approach to print currency values without the currency sign in pure Java code is to get a general-purpose NumberFormat instance and configure it to use the number of digits defined by the appropriate Currency object:

NumberFormat numberFormat = NumberFormat.getInstance(myLocale);
Currency currency = Currency.getInstance(myLocale);
numberFormat.setMinimumFractionDigits(currency.getDefaultFractionDigits());

If you need a specific currency as opposed to the default currency of the locale you use, use the String override of Currency.getInstance() instead and provide the appropriate currency code.



来源:https://stackoverflow.com/questions/54439562/java-numbervalue-to-string-without-currency-sign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!