[英]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;最后一行以NumberFormatException失败,因为小数用逗号分隔;
I am using windows OpenJDK8:我正在使用 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. DecimalFormat
仅用于格式化值。 Double.valueOf
doesn't know the format and expect a .
Double.valueOf
不知道格式并期望.
if you want to parse duch string you have to use DecimalFormat
for parsing this value:如果你想解析 duch 字符串,你必须使用
DecimalFormat
来解析这个值:
return df.parse(df.format(monthlyVal));
The cause is the Locale
.原因是
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:要使用 DecimalFormat 进行更改,请执行以下操作:
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.恕我直言,我建议在此类用例中使用 BigDecimal,因为它更准确,更不容易出错,并且可以轻松处理舍入、缩放等的使用。
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");
当你写
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.
你可以改变你的语言环境。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.