如何使用DecimalFormat格式化货币?

投票:

输入看起来像8.7000000,我想将其格式化为8.70 EUR我考虑使用DecimalFormat该类:

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

结果是8.7 EUR我怎样才能告诉格式化程序在.后面有两位数字

Matt Fellows:

在这里还想强调一下Jon Skeet关于使用整数存储所有货币的观点-不想用金钱来处理浮点舍入错误。

使用.00而不是.##- 0表示一个数字,#表示一个数字(但是如果它等于零,则将其隐藏)。

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

或使用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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章