Search code examples
javabigdecimal

Convert to correct BigDecimal representation


I have a string being returned as a data feed which I need to convert to the correct BigDecimal format - the string is of the format

1.6945E3

and needs to translate to 1694.50 but instead translates only to 1694.5 leading to loss of information. The following is the code I am using.

I am just passing the string and doing a new on a instance of BigDecimal.

Any ideas on how to get the correct data representation.

Thanks '


Solution

  • it depends, try this

        BigDecimal bd = new BigDecimal("1694.50");
        System.out.println(bd);
    

    output

    1694.50
    

    but this

        BigDecimal bd = new BigDecimal(1694.50);
        System.out.println(bd);
    

    produces

    1694.5
    

    and this

        BigDecimal bd = new BigDecimal("1694.50");
        System.out.printf("%.3f", bd);
    

    prints

    1694.500