Search code examples
javabigdecimaldecimalformat

Strange BigDecimal value using DecimalFormat


I'm trying to convert some string values in number using DecimalFormat. I try to explain you my problem in a better way:

I have the following method:

private BigDecimal loadBigDecimal(String value){

    BigDecimal bigDecimalToReturn = null;
    DecimalFormat df = new DecimalFormat("##.###");
    bigDecimalToReturn = new BigDecimal(df.parse(value).doubleValue());
    return bigDecimalToReturn;
}

Now if I try to run the method:

BigDeciaml dec = myObject.loadBigDecimal("120,11");

The value of dec is 120.1099999999999994315658113919198513031005859375. Why decimalFormat is changing the scale of my value?


Solution

  • You are doing conversion to double and backwards. That's unnecessary and introduces rounding errors. You should use the following code:

    private BigDecimal loadBigDecimal(String value) throws ParseException {
        DecimalFormat df = new DecimalFormat("##.###");
        df.setParseBigDecimal(true);
        return (BigDecimal) df.parse(value);
    }