DecimalFormat 取决于系统设置?
我遇到了关于 DecimalFormat 的最奇怪的事情。
我在网络应用程序中使用它。 我设置了一些测试,但它在本地一直失败。 我的一个朋友运行了它,他能够成功运行 JUnit 测试。
奇怪的是,在我们的服务器上,应用程序运行得很好,没有任何问题。
难道Java依赖于系统设置,比如值和数字设置? 或者还有其他原因吗? 这就是我的代码的样子:
public String generateFormatPrice(double price) throws Exception {
DecimalFormat format1 = new DecimalFormat("#,##0.00");
String tmp = format1.format(price).replace(".", "&");
String[] tmps = tmp.split("&");
return tmps[0].replace(',', '.') + "," + tmps[1];
}
提前非常感谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该代码确实是特定于语言环境的。如果您的代码取决于所在区域,例如美国,其中“.”是小数分隔符,“,”是千位分隔符,然后您在设置为德语语言环境的服务器上运行此代码,它将失败。
考虑使用这个 构造函数,它允许您显式指定您正在使用的符号。
编辑:据我所知,您正在尝试使用“.”来格式化数字。作为千位分隔符,“,”作为小数分隔符。换句话说,法国和德国使用的格式。这是实现此目的的一种方法:
此外,您不应该使用双精度数来保存货币值 - 如果您这样做,您将遇到一些讨厌的错误。
This code is indeed locale-specific. If your code depends on being in a locale such as the USA where "." is the decimal separator and "," is the thousands separator, and then you run this code on a server set to, for example, the German locale, it will fail.
Consider using this constructor, which allows you to explicitly specify which symbols you are using.
EDIT: as far as I can tell you are trying to format numbers using "." as the thousands separator and "," as the decimal separator. In other words, the format used in France and Germany. Here's one approach that will achieve this:
Also, you shouldn't be using a double to hold a monetary value - you are going to encounter some nasty bugs if you do that.