How to use DecimalFormat to format money?
Asked Answered
H

3

14

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 .?

Hotshot answered 21/12, 2011 at 13:41 Comment(1)
In general, you shouldn't be using binary floating point types to store currency values anyway. Use BigDecimal or just scale an integer (e.g. have an integer number of cents).Picard
B
29

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);
Bortz answered 21/12, 2011 at 13:42 Comment(3)
How would the format look like if I have 0.0600 as input and want 6,0 ct as output?Hotshot
You'd have to do that in code I'm afraid - the Decimal format wouldn't cope with changing the unit. I guess have a condition `if (val < 1 && val > 0){ //multiply by 100 and use ct formatter } else { //use eur formatter }Bortz
Did you see the point about using integers? It's a good idea. Using floats, or doubles, will lead to errors.Bortz
S
5

I found a nice solution in this link below

http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

in short to represent a currency like 92323345465.30 as 92,323,345,465.30 just use ###,###,###,###.00

That is, whenever you use '0', then the '0' will either be replaced by another digit, or if there is no digit to replace it, then IT WILL APPEAR! But is you use '#' then if there is no number to replace the '#', then that space will be empty.

Remember that you can even add up your own symbols like $, etc in front of the formatting or even after the formatting string

Stromberg answered 2/12, 2013 at 11:9 Comment(0)
A
4

I think a good option would be this aproach:

Using #,###.00 the result for the value 0.50 would be displayed like this:

$.50

However, if you use #,##0.00 the result for the same value would be:

$0.50

Advection answered 19/10, 2017 at 13:18 Comment(2)
but why is it 0,50 and not 0.50?Fibroma
Because the comma is used from the thousand place.Theocrasy

© 2022 - 2024 — McMap. All rights reserved.