我正在尝试将 NumberValue 格式化为当前区域设置格式的字符串。
例如,对于 Locale.Germany,这些将是我试图获得的结果:
1 -> 1,00
1.1 -> 1,10
0.1 -> 0,10
我尝试过的:
String test1 = NumberFormat.getInstance().format(1.1);
// -> 1,1
String test2 = NumberFormat.getCurrencyInstance().format(1.1);
// -> 1,10 €
如何获得与第二个示例相同的格式,而不需要货币符号?或者,我如何确保第一个示例的结果始终具有当前区域设置所需的小数位数?
编辑:由于有些货币有 0、2 或 3 位小数,我认为将小数设置为固定金额不会产生正确的结果。
此外,有些货币的符号在前面,有些在后面,因此切断最后一个字符可能也不起作用。
http://apps.cybersource.com/library/documentation/sbc/quickref/currencies.pdf
最佳答案
java.util.Currency
提供必要的信息。在纯 Java 代码中打印没有货币符号的货币值的合理方法是获取通用的 NumberFormat
实例并将其配置为使用由适当的 Currency
对象定义的位数:
NumberFormat numberFormat = NumberFormat.getInstance(myLocale);
Currency currency = Currency.getInstance(myLocale);
numberFormat.setMinimumFractionDigits(currency.getDefaultFractionDigits());
如果您需要特定货币而不是您使用的区域设置的默认货币,请使用 the String
override of Currency.getInstance()
相反,并提供适当的货币代码。
关于Java - NumberValue 到没有货币符号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54439562/