【问题标题】:Float number formatting issue [duplicate]浮点数格式问题[重复]
【发布时间】:2013-05-10 10:24:30
【问题描述】:
我正在使用此代码:
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
float a=(float) 15000.345;
Sytem.out.println(df.format(a));
我得到这个输出:15,000.35
我不希望逗号出现在此输出中。
我的输出应该是:15000.35。
在 Java 中获得此输出的最佳方法是什么?
【问题讨论】:
标签:
java
numbers
number-formatting
decimalformat
【解决方案1】:
阅读 javadoc 并使用它:
df.setGroupingUsed(false);
【解决方案2】:
试试
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setGroupingUsed(false);
float a=(float) 15000.345;
System.out.println(df.format(a));
和
Sytem.out.println(df.format(a)); //wrong //sytem
System.out.println(df.format(a));//correct //System
【解决方案3】:
应该设置分组大小。默认值为 3。见Doc.
df.setGroupingSize(0);
或者你使用 setGroupingUsed。
df.setGroupingUsed(false);
您的完整代码
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setGroupingUsed(false);
float a=(float) 15000.345;
Sytem.out.println(df.format(a));
【解决方案4】:
您也可以将#####.## 作为模式传递
DecimalFormat df = new DecimalFormat("#####.##");
【解决方案5】:
你可以这样做:
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.');
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);
之后就像你所做的那样:
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
float a=(float) 15000.345;
System.out.println(df.format(a));
这将为您提供预期的结果。