简体   繁体   English

DecimalFormat.parse() 忽略指数

[英]DecimalFormat.parse() ignoring exponents

I am trying to parse Strings containing decimals (that may or may not use scientific notation) into BigDecimal .我正在尝试将包含小数(可能使用也可能不使用科学记数法)的字符串解析为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). DecimalFormat.parse()似乎适用于不使用科学记数法的数字,但3.95e-06被解析为双3.95 (指数被忽略)。

I am familiar with the BigDecimal(String) constructor but DecimalFormat affords me a more flexible parsing format (eg for currencies).我熟悉BigDecimal(String)构造函数,但DecimalFormat为我提供了更灵活的解析格式(例如货币)。

What is the appropriate way to parse decimals, with or without exponential notation, into BigDecimal ?使用或不使用指数表示法将小数解析为BigDecimal的适当方法是什么?

Apparently DecimalFormat expects a capital E and not a lowercase e , per this answer .显然,根据此答案DecimalFormat需要大写的E不是小写的e

But you can always uppercase the string.但是您始终可以将字符串大写。 Then you can call setParseBigDecimal and set it to true so that parse returns a BigDecimal .然后您可以调用setParseBigDecimal并将其设置为true以便parse返回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:输出:每个字符串的doubleBigDecimal输出:

3.95E-6
0.00000395
12345.0
12345

DecimalFormat seems to be thrown off by the lowercase e . DecimalFormat似乎被小写e抛弃了。 Per https://stackoverflow.com/a/13925393/14731 this doesn't seem to be fixable.根据https://stackoverflow.com/a/13925393/14731,这似乎无法解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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