DecimalFormat取决于系统设置吗? [英] DecimalFormat depending on system settings?

查看:54
本文介绍了DecimalFormat取决于系统设置吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最奇怪的是使用DecimalFormat.

I'm having the strangest thing with a DecimalFormat.

我正在Web应用程序中使用它.我设置了一些测试,并且在本地持续失败.我的一个朋友运行了它,他能够成功运行JUnit测试.

I'm using it in an webapplication. I setup some test and it keeps on failing with me locally. A friend of me ran it and he was able to successfully ran the JUnit tests.

奇怪的是,在我们的服务器上,应用程序可以完美地运行它,也没有任何问题.

The strange part is that on our server the application runs it perfectly without any problems either.

难道Java取决于诸如valuta和数字设置之类的系统设置?还是有其他原因?这是我的代码的样子:

Could it be that Java depends on the system settings like valuta and number settings? Or could there be another reason? This is how my piece of code looks like:

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];
}

非常感谢!

推荐答案

此代码确实是特定于语言环境的.如果您的代码依赖于位于."等美国的语言环境.是小数点分隔符,,"是千位分隔符,然后在设置为例如德国语言环境的服务器上运行此代码,它将失败.

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.

据我所知,您正在尝试使用."格式化数字.作为千位分隔符,,"作为十进制分隔符.换句话说,在法国和德国使用的格式.这是一种可以实现此目的的方法:

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:

public static String generateFormatPrice(double price) {
    final NumberFormat format = NumberFormat.getNumberInstance(Locale.GERMANY);
    format.setMinimumFractionDigits(2);
    format.setMaximumFractionDigits(2);
    return format.format(price);
}

此外,您不应该使用双精度来持有货币值-如果这样做,您将遇到一些讨厌的错误.

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.

这篇关于DecimalFormat取决于系统设置吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆