简体   繁体   中英

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 (eg for currencies).

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

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

DecimalFormat seems to be thrown off by the lowercase e . Per https://stackoverflow.com/a/13925393/14731 this doesn't seem to be fixable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM