简体   繁体   English

使用 Double.parseDouble() 时如何禁用自动转换为指数表达式?

[英]How to disable auto-converting to exponential expression when using Double.parseDouble()?

When I run the following program:当我运行以下程序时:

System.out.println(Double.parseDouble("99999999999999") + 1);

I got: 1.0E14我得到: 1.0E14

How can I disable the auto-conversion so that I get 100000000000000.0 ?如何禁用自动转换以便获得100000000000000.0

That has nothing to do with Double.parseDouble , and everything to do with Double.toString .这与Double.parseDouble无关,与Double.toString

Try this:尝试这个:

System.out.printf("%.1f", Double.parseDouble("99999999999999") + 1);

Use aBigDecimal instead.请改用BigDecimal

    import java.math.BigDecimal;

    BigDecimal big = new BigDecimal("99999999999999");
    big = big.add(BigDecimal.ONE); // Thanks @Chris for this tip
    System.out.println(big); // Prints "100000000000000"

BigNumbers offer arbitrary precision. BigNumbers 提供任意精度。 Double is limited to an (approximated) 64-bit representation. Double 仅限于(近似的)64 位表示。 If you were to use too many 9's, you would get the wrong answer:如果你使用太多的 9,你会得到错误的答案:

    System.out.printf("%.1f", Double.parseDouble("9999999999999998") + 1); // Note ends in 8

This prints "10000000000000000.0" , which is incorrect, should be "9999999999999999.0" , but the number has exceeded the accuracy of Double这打印"10000000000000000.0" ,这是不正确的,应该是"9999999999999999.0" ,但是数字已经超过了 Double 的精度

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

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