How to change the decimal separator of DecimalFormat from comma to dot/point?
我有这个疯狂的方法,可以将BigDecimal值转换为漂亮且可读的字符串。
1 2 3 4 5 6 7 8 9 | private String formatBigDecimal(BigDecimal bd){ DecimalFormat df = new DecimalFormat(); df.setMinimumFractionDigits(3); df.setMaximumFractionDigits(3); df.setMinimumIntegerDigits(1); df.setMaximumIntegerDigits(3); df.setGroupingSize(20); return df.format(bd); } |
但是,它还会产生一个所谓的分组分隔符
1 | xxx,xxx |
我确实需要分隔符是点或点而不是逗号。
有人知道如何完成这一小壮举吗?
我已经读过这本书,尤其是现在读到了死刑,但我找不到解决方法。
我是否以错误的方式处理此问题? 有更优雅的方法吗? 甚至可能是一个解决方案,说明了不同的本地数字表示形式,因为按照欧洲标准,逗号是完美的。
您可以通过设置区域设置或使用DecimalFormatSymbols来更改分隔符。
如果希望分组分隔符成为一个点,则可以使用欧洲语言环境:
1 2 | NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN); DecimalFormat df = (DecimalFormat)nf; |
或者,您可以使用DecimalFormatSymbols类来更改出现在format方法生成的带格式数字中的符号。这些符号包括小数点分隔符,分组分隔符,减号和百分号,以及其他:
1 2 3 4 | DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale); otherSymbols.setDecimalSeparator(','); otherSymbols.setGroupingSeparator('.'); DecimalFormat df = new DecimalFormat(formatString, otherSymbols); |
可以从Locale.getDefault()获得currentLocale,即:
欧洲非常庞大。我不确定他们是否全部使用相同的格式。但是,这个或这个答案将有所帮助。
1 2 3 4 5 6 7 | String text ="1,234567"; NumberFormat nf_in = NumberFormat.getNumberInstance(Locale.GERMANY); double val = nf_in.parse(text).doubleValue(); NumberFormat nf_out = NumberFormat.getNumberInstance(Locale.UK); nf_out.setMaximumFractionDigits(3); String output = nf_out.format(val); |
即使用正确的语言环境。
1 2 3 4 5 | public String getGermanCurrencyFormat(double value) { NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN); nf.setGroupingUsed(true); return"€" + nf.format(value); } |
BigDecimal似乎不遵守区域设置。
1 |
斯洛文尼亚语言环境应使用小数逗号。猜猜我对数字有奇怪的误解。
1 2 3 4 | a = new BigDecimal("1,2") //throws exception a = new BigDecimal("1.2") //is ok a.toPlainString() // returns"1.2" always |
我已经编辑了部分消息,因为它被证明是人为错误(忘记提交数据,而正在寻找错误的东西),因此没有意义。
对于任何Java .toString()函数,都可以说与BigDecimal相同。我想这在某些方面是好的。例如序列化或调试。有一个唯一的字符串表示形式。
正如其他人提到的使用格式化程序也可以。只需使用格式化程序(与JSF前端相同),格式化程序即可正确完成工作并了解语言环境。
1 |
Just replace '.' with ',' in the UI end
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import java.text.DecimalFormat; public MyClass{ private String netAmount; private static DecimalFormat twoDecimalForm = new DecimalFormat("00.00"); public MyClass(double amount){ //converting to required decimal format in constructor or/and setter this.amount=twoDecimalForm.format(amount); } public String getAmount() { //replacing decimal point with comma so that in JSP ELs you'll get it in comma format return amount.replace(".",","); } public void setAmount(String amount) { this.amount = amount; } } |