简体   繁体   English

当数字超过1234567891123456时,DecimalFormat解析双重错误

[英]DecimalFormat parse double error when number over 1234567891123456

I get an unexpected result when I try to parse string 12345678911234567 to double. 当我尝试将字符串12345678911234567解析为double时,我得到了意外的结果。 I use the code as below 我使用如下代码

    double convertedNum = 0;
convertedNum = new DecimalFormat().parse(12345678911234567).doubleValue();

the converted result was 1.2345678911234568E16 but I expected it was 1.2345678911234567E16, and I also try to use BigDecimal to convert as below 转换结果是1.2345678911234568E16,但我预计它是1.2345678911234567E16,我也尝试使用BigDecimal转换如下

double convertedNum = 0;
BigDecimal bgNum = null;
bgNum = new BigDecimal(12345678911234567);
convertedNum = bgNum.doubleValue();

will get same result, I can't find what cause this. 会得到相同的结果,我找不到导致这个的原因。 Would someone can give me some suggests, thanks. 有人可以给我一些建议,谢谢。

My best suggestion is to put the number in quote marks in the BigDecimal constructor - like 我最好的建议是将数字放在BigDecimal构造函数中的引号中 - 就像

new BigDecimal("12345678911234567");

The constructor of BigDecimal with a String argument can deal with numbers of (just about) any reasonable size. 具有String参数的BigDecimal的构造函数可以处理任何合理大小的数量(几乎)。

Not all large numbers can be stored correctly in a double . 并非所有大数字都可以正确存储在double It seems that the number you're trying to represent may fall in between two double values. 您尝试表示的数字似乎可能介于两个double值之间。 But BigDecimal will certainly be able to represent it correctly. 但是BigDecimal肯定能够正确地表示它。

Update 更新

To clarify my last paragraph, there is no double equal to 12345678911234567 . 为澄清我的最后一段,没有double等于12345678911234567 There is a double equal to 12345678911234566 , but the next double is equal to 12345678911234568 . 有一个等于12345678911234566double ,但下一个double等于12345678911234568 So any attempt whatsoever to store 12345678911234567 in a double will result in rounding up to 12345678911234568 . 因此,任何将12345678911234567存储在double任何尝试都将导致四舍五入为12345678911234568

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

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