在使用 toString()
方法时,Double 类型会自动添加逗号(例如 5143 会被打印为 5,143)。如何禁止这种行为?
在使用 toString()
方法时,Double 类型会自动添加逗号(例如 5143 会被打印为 5,143)。如何禁止这种行为?
你的问题属于Locale范畴,正如Rorick所指出的那样。然而,如果改变Locale会导致一切混乱,你应该查看DecimalFormat类。
查看NumberFormat类,处理千位分隔符。因为似乎你的情况是关于千位分隔符的。
这将删除所有分组(在您的情况下是逗号)。
DecimalFormat df = new DecimalFormat();
df.setGroupingUsed(false);
toString()
方法返回的内容。someDouble.toString().replaceAll(",", "");
这并不是最优雅的解决方案,但它能够运行。
如果只是你的程序是为了你个人家庭使用而已。<恰恰相反。 - Kai Huppmann
Java使用NumberFormat类提供了出色的本地化数字格式化支持:
使用当前语言环境:
NumberFormat.getNumberInstance().format(5000000);
使用瑞典语区域设置将获得字符串:5 000 000
...或者使用特定的区域设置(例如法语,也会得到5 000 000):
NumberFormat.getNumberInstance(Locale.FRANCE).format(5000000);
myDouble.toString().replaceAll(",", "");
Double
会添加逗号。所以,我倾向于同意他的观点。我认为他需要回来澄清这里的困惑。 - Adeel Ansari三种方式:
Using the DecimalFormat
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
dfs.setGroupingSeparator(Character.MAX_VALUE);
df.setDecimalFormatSymbols(dfs);
System.out.println(df.format(doubleVar));
(as suggested by others) just replace the comma in the string that you get
public String formatNumber(double number){
NumberFormat nf = NumberFormat.getInstance(new Locale("en", "EN"));
nf.setMaximumFractionDigits(3);
nf.setMinimumFractionDigits(1);
nf.setGroupingUsed(false);
String str = nf.format(number);
return str;
}
NumberFormat format = NumberFormat.getInstance();
format.setGroupingUsed(false);
这段代码是用于格式化数字的。第一行代码创建了一个NumberFormat实例,该实例可以用来格式化数字。第二行代码将设置不使用分组符号,即千位分隔符。Double result= 5143.0;
Sysout(result.toString())
给了我 5143.0...
你能把你得到的代码放上来吗
,
是数字分组符号,而小数分隔符是.
。因此,在美国环境中看起来像5143.5
的数字,在俄罗斯环境中则是5,143.5
。 - Rorick