How to use DecimalFormat to format money?

Upvote picture Upvote · Dec 21, 2011 · Viewed 30.8k times · Source

The input looks like 8.7000000 and I want to format it to look like 8.70 EUR. I considered using the DecimalFormat class:

Double number = Double.valueOf(text);

DecimalFormat dec = new DecimalFormat("#.## EUR");
String credits = dec.format(number);

TextView tt = (TextView) findViewById(R.id.creditsView);
tt.setText(credits);

The result is 8.7 EUR. How can I tell the formatter to have two digits after the .?

Answer

Matt Fellows picture Matt Fellows · Dec 21, 2011

Also want to highlight here Jon Skeet's point about using integers to store all your currency - don't want to be dealing with floating-point rounding errors with money.

Use .00 instead of .## - 0 means a digit, # means a digit (but hide it if it's equal to zero).

Double number = Double.valueOf(text);

DecimalFormat dec = new DecimalFormat("#.00 EUR");
String credits = dec.format(number);

TextView tt = (TextView) findViewById(R.id.creditsView);
tt.setText(credits);

Or use setMinimumFractionDigits:

Double number = Double.valueOf(text);

DecimalFormat dec = new DecimalFormat("#.## EUR");
dec.setMinimumFractionDigits(2);
String credits = dec.format(number);

TextView tt = (TextView) findViewById(R.id.creditsView);
tt.setText(credits);