Java:浮点格式取决于区域设置
我住在比利时。一般来说,在数学中,我们用逗号来写小数,如下所示:3,141592
这也是我格式化浮动时的结果。
System.out.println(String.format("%f", 3.141592));
因此,.
被 ,
替换,如下所示:3,141592
。因此,当我需要一个点时,我总是必须添加如下内容: String.format("%f", 3.14).replace(',','.');
所以,问题是:有没有一种方法可以更改区域设置,使 Java 中的每个格式化程序都使用点而不是逗号?
感谢
System.out.println(Locale.getDefault());
印刷品
nl_BE
I live in Belgium. And generally, in mathematics, we write our decimals with a comma like this: 3,141592
And that is also the result when I format the float.
System.out.println(String.format("%f", 3.141592));
So, the .
is replaced by a ,
like so: 3,141592
. So always when I need a point instead I have to add something like this: String.format("%f", 3.14).replace(',','.');
So, the question is: is there a way to change the Locale which makes every formatter in Java use a point, instead of comma?
Thanks
System.out.println(Locale.getDefault());
prints
nl_BE
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用 String.format(Locale.US, "%f", floatValue) 来设置格式化期间使用的区域设置。
Try using
String.format(Locale.US, "%f", floatValue)
for just setting locale used during formatting.一个简单的解决方案是将系统区域设置设置为美国或英国,但会广泛影响整个区域设置。例子。
既然您已经更改了问题,那么您只需使用打印方法指定本地即可。
A simple solution, but would be wide reaching across the entire Locale, would be to set the system Locale to US or UK. Example.
Since you have changed the question, then you simply specify the local with your print method.
看看可能有用
http://download.oracle.com/javase/6 /docs/api/java/text/DecimalFormat.html
其中包含许多选项,可在必要时使用 Locale 精确输出字符串
通过定制例程路由输入和输出通常很有用。这是 JAMA 库 (http://math.nist.gov/javanumerics/jama/) 中的一个,
通过使用它,您可以确保将来的问题和增强功能可能得到解决
It may be useful to look at
http://download.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
which contains a number of options for precise output of strings using Locale where necessary
It is often useful to route input and output through bespoke routines. Here is one from the JAMA library (http://math.nist.gov/javanumerics/jama/)
By using this you can be sure that future problems and enhancements are likely to be addressed
对于格式化数字,您确实不应该依赖
toString()
。使用String.format()
、NumberFormat
中的工厂方法或DecimalFormat
,它们允许您控制数字的格式化方式(前两个通过选择区域设置)而不依赖于某些全局设置。For formatting numbers, you really should not rely on
toString()
. UseString.format()
, the factory methods inNumberFormat
, orDecimalFormat
, which allow you to control how numbers are formatted (the first two by choosing a Locale) without relying on some global setting.