DecimalFormat.parse() 忽略指数

DecimalFormat.parse() ignoring exponents

我正在尝试将包含小数的字符串(可能使用也可能不使用科学记数法)解析为 BigDecimal

DecimalFormat.parse() 似乎适用于不使用科学计数法的数字,但 3.95e-06 被解析为双 3.95 (指数被忽略)。

我熟悉 BigDecimal(String) 构造函数,但 DecimalFormat 为我提供了更灵活的解析格式(例如货币)。

将带或不带指数表示法的小数解析为 BigDecimal 的适当方法是什么?

DecimalFormat 好像被小写的 e 甩掉了。根据 这似乎无法修复。

显然 DecimalFormat 需要大写字母 E 不是 小写字母 e,根据 this answer.

但您始终可以将字符串大写。然后你可以调用 setParseBigDecimal 并将其设置为 true 以便 parse returns a BigDecimal.

测试科学和正常的符号:

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);
}

输出:double 然后是每个字符串的 BigDecimal 输出:

3.95E-6
0.00000395
12345.0
12345