How to use DecimalFormat to format money?

流过昼夜 提交于 2019-12-06 19:54:36

问题


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


回答1:


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



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/8590718/how-to-use-decimalformat-to-format-money

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