DecimalFormat depending on system settings?

女生的网名这么多〃 提交于 2021-01-28 03:04:50

问题


I'm having the strangest thing with a DecimalFormat.

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.

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

Thanks a lot in advance!


回答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:

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.



来源:https://stackoverflow.com/questions/8742645/decimalformat-depending-on-system-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!