简体   繁体   中英

DecimalFormat uses comma separator even when the pattern specified is a dot

I have the below code for formatting a double to two decimal places;

DecimalFormat df = new DecimalFormat("0.00");
double monthlyVal = forecastReturnValue / months;
return Double.valueOf(df.format(monthlyVal));

The last line fails with a NumberFormatException because decimals are separated by a comma;

截屏

I am using windows OpenJDK8:

openjdk version "1.8.0_41"
OpenJDK Runtime Environment (build1.8.0_41-b04)
OpenJDK Client VM (build 25.40-b25, mixed mode)

What could be the cause?

The DecimalFormat ist only for formating the value. Double.valueOf doesn't know the format and expect a . if you want to parse duch string you have to use DecimalFormat for parsing this value:

return df.parse(df.format(monthlyVal));

The cause is the Locale . By default, you are connected to the Locale on your system, which return a decimal separator as , . Using DecimalFormat, to change, do the following:

DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
DecimalFormat df = new DecimalFormat("0.00", symbols);
double monthlyVal = forecastReturnValue / months;
return Double.valueOf(df.format(monthlyVal));

IMHO, I'd recommend using BigDecimal for such use cases, as it is more accurate, less error prone, and handle easily usage of rounding, scaling and so on.

The equivalent could be:

BigDecimal monthlyVal = BigDecimal.valueOf(20.0).divide(BigDecimal.valueOf(12), 2, RoundingMode.CEILING); // 2 is the scale. RoundingMode is up to you
System.out.println(monthlyVal);

When you write new DecimalFormat("0.00"); you are not specifying the separator type. You are just specifying that there should be a separator. The separator will still be based on your locale.

Format Strings us "." as the decimal separator.

If you want to use a '.' you can change your locale.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM