lis*_*aro 11 java decimalformat
我正在尝试格式化字符串以在3位组之间添加逗号
例如:
1200.20 >> 1,200.20
15000 >> 15,000
Run Code Online (Sandbox Code Playgroud)
我正在试图弄清楚如何用DecimalFormat做到这一点,到目前为止我一直在使用我自己的一个看起来过于复杂的脚本.我无法弄清楚如何做到这一点,使用#只隐藏尾随零并使用0将它们添加到数字中.
这就是我现在正在尝试的:
DecimalFormat df = new DecimalFormat("###,###.####", new DecimalFormatSymbols(Locale.US));
resultStr = df.format(Double.valueOf(resultStr));
Run Code Online (Sandbox Code Playgroud)
我敢肯定它一定很容易,但我不知道该怎么做.我不需要使用DecimalFormat,我只是认为这将是更简单的方法.如何在不修改小数的情况下简单地添加逗号?
Hov*_*els 20
您应该使用NumberFormat对象并将其设置为使用分组.就像是
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
public class NumberFormatEg {
public static void main(String[] args) {
NumberFormat myFormat = NumberFormat.getInstance();
myFormat.setGroupingUsed(true);
double[] numbers = { 11220.00, 232323232.24, 121211.55, 102.121212 };
for (double d : numbers) {
System.out.println(myFormat.format(d));
}
System.out.println();
DecimalFormat decimalFormat = new DecimalFormat("#.00");
decimalFormat.setGroupingUsed(true);
decimalFormat.setGroupingSize(3);
for (double d : numbers) {
System.out.println(decimalFormat.format(d));
}
System.out.println("\nFor Germany");
NumberFormat anotherFormat = NumberFormat
.getNumberInstance(Locale.GERMAN);
if (anotherFormat instanceof DecimalFormat) {
DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
anotherDFormat.applyPattern("#.00");
anotherDFormat.setGroupingUsed(true);
anotherDFormat.setGroupingSize(3);
for (double d : numbers) {
System.out.println(anotherDFormat.format(d));
}
}
System.out.println("\nFor US:");
anotherFormat = NumberFormat.getNumberInstance(Locale.US);
if (anotherFormat instanceof DecimalFormat) {
DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
anotherDFormat.applyPattern("#.00");
anotherDFormat.setGroupingUsed(true);
anotherDFormat.setGroupingSize(3);
for (double d : numbers) {
System.out.println(anotherDFormat.format(d));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
返回:
11,220
232,323,232.24
121,211.55
102.121
11,220.00
232,323,232.24
121,211.55
102.12
For Germany
11.220,00
232.323.232,24
121.211,55
102,12
For US:
11,220.00
232,323,232.24
121,211.55
102.12
Run Code Online (Sandbox Code Playgroud)
这样做的一个优点是解决方案可以是特定于区域的.
Edited
Now显示了一个带有DecimalFormat对象的示例.请注意,如果使用此选项,则应设置分组大小.
ars*_*jii 12
你也可以尝试类似的东西
DecimalFormat df = new DecimalFormat("#,###.00");
System.out.println(df.format(1200.20));
System.out.println(df.format(15000));
System.out.println(df.format(123456789.99));
Run Code Online (Sandbox Code Playgroud)
1,200.20 15,000.00 123,456,789.99