greenthunder
greenthunder

Reputation: 727

How to set customize currency in java?

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?

Upvotes: 13

Views: 14383

Answers (3)

mprivat
mprivat

Reputation: 21902

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

Upvotes: 30

JB Nizet
JB Nizet

Reputation: 691765

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.

Upvotes: 1

Moritz Petersen
Moritz Petersen

Reputation: 13057

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().

Upvotes: 4

Related Questions