Ski*_*zzo 1 java bigdecimal decimalformat
我正在尝试使用DecimalFormat转换一些字符串值.我试着用更好的方式向你解释我的问题:
我有以下方法:
private BigDecimal loadBigDecimal(String value){
BigDecimal bigDecimalToReturn = null;
DecimalFormat df = new DecimalFormat("##.###");
bigDecimalToReturn = new BigDecimal(df.parse(value).doubleValue());
return bigDecimalToReturn;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我尝试运行该方法:
BigDeciaml dec = myObject.loadBigDecimal("120,11");
Run Code Online (Sandbox Code Playgroud)
dec的值是120.1099999999999994315658113919198513031005859375.为什么decimalFormat会改变我的值的范围?
你正在转换为双向和向后.这是不必要的,并引入了舍入错误.您应该使用以下代码:
private BigDecimal loadBigDecimal(String value) throws ParseException {
DecimalFormat df = new DecimalFormat("##.###");
df.setParseBigDecimal(true);
return (BigDecimal) df.parse(value);
}
Run Code Online (Sandbox Code Playgroud)