How to set customize currency in java?

一曲冷凌霜 提交于 2020-01-13 08:30:35

问题


I tried to make manual currency. Here is my code

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setCurrencySymbol("$");
dfs.setGroupingSeparator('.');
dfs.setDecimalSeparator('.');
df.setDecimalFormatSymbols(dfs);
System.out.println(df.format(3333454));

Program output is

3.333.454

Why the currency symbol I set didn't appear?


回答1:


Try this:

NumberFormat df = NumberFormat.getCurrencyInstance();
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setCurrencySymbol("$");
dfs.setGroupingSeparator('.');
dfs.setMonetaryDecimalSeparator('.');
((DecimalFormat) df).setDecimalFormatSymbols(dfs);
System.out.println(df.format(3333454));



回答2:


Because you use the DecimalFormat with the standard pattern. You need to provide your custom pattern with the \u00A4 currency symbol.

Or you use NumberFormat.getCurrencyInstance().




回答3:


You've told the DecimalFormat which currency symbol to use when it must format a currency. But you haven't told it to format a currency. The default pattern used by the no-arg constructor isn't meant to format currencies. Use a dedicated pattern for that.

The javadoc tells you everything you need to know.



来源:https://stackoverflow.com/questions/10536899/how-to-set-customize-currency-in-java

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