您应该使用 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));
}
}
}
}
返回:
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
这样做的一个优点是解决方案可以是特定于语言环境的。
Edited
Now 显示了一个带有 DecimalFormat 对象的示例。请注意,如果您使用它,您应该设置分组大小。