java 如何在java中设置自定义货币?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10536899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:28:50  来源:igfitidea点击:

How to set customize currency in java?

javaformatsetcurrency

提问by greenthunder

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

3.333.454

Why the currency symbol I set didn't appear?

为什么我设置的货币符号没有出现?

回答by mprivat

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));

回答by Moritz Petersen

Because you use the DecimalFormatwith the standard pattern. You need to provide your custom pattern with the \u00A4currency symbol.

因为您使用DecimalFormat标准模式。您需要提供带有\u00A4货币符号的自定义模式。

Or you use NumberFormat.getCurrencyInstance().

或者你使用NumberFormat.getCurrencyInstance().

回答by JB Nizet

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.

您已经告诉 DecimalFormat 在必须格式化货币时使用哪个货币符号。但是你还没有告诉它格式化货币。无参数构造函数使用的默认模式并不意味着格式化货币。为此使用专用模式。

The javadoctells you everything you need to know.

javadoc 会告诉您需要知道的一切。