Search code examples
javaparsingbigdecimal

DecimalFormat.parse() ignoring exponents


I am trying to parse Strings containing decimals (that may or may not use scientific notation) into BigDecimal.

DecimalFormat.parse() seems to work fine for numbers that do not use scientific notation, but 3.95e-06 is getting parsed as the double 3.95 (the exponent is being ignored).

I am familiar with the BigDecimal(String) constructor but DecimalFormat affords me a more flexible parsing format (e.g. for currencies).

What is the appropriate way to parse decimals, with or without exponential notation, into BigDecimal?


Solution

  • Apparently DecimalFormat expects a capital E and not a lowercase e, per this answer.

    But you can always uppercase the string. Then you can call setParseBigDecimal and set it to true so that parse returns a BigDecimal.

    Testing scientific and normal notation:

    public static void main(String[] args) throws Exception
    {
        test("3.95e-06");
        test("12345");
    }
    
    private static void test(String line) throws Exception {
        DecimalFormat bdf = new DecimalFormat();
        double d = bdf.parse(line.toUpperCase()).doubleValue();
        System.out.println(d);
        bdf.setParseBigDecimal(true);
        BigDecimal test = (BigDecimal) bdf.parse(line.toUpperCase());
        System.out.println(test);
    }
    

    Output: The double then the BigDecimal output for each string:

    3.95E-6
    0.00000395
    12345.0
    12345