简体   繁体   English

双重精度损失

[英]Double Lost Of Precision

I'm a little bit confused because I lose precision all the time. 我有点困惑,因为我一直都在失去精度。

Maybe I'm operating with the wrong type. 也许我使用的是错误的类型。 I have a String like "100.00". 我有一个类似“ 100.00”的字符串。 But when I do 但是当我这样做

Double.parseDouble("100.00") it is being cut off to 100. Need help. Double.parseDouble(“ 100.00”)被截断为100。需要帮助。 Thanks in advance. 提前致谢。

You probably printed your number with System.out.println(d) . 您可能使用System.out.println(d)打印了您的号码。 It will internally call Double.toString(double) , whose specification states 它将内部调用Double.toString(double) ,其规范状态

How many digits must be printed for the fractional part of m or a? m或a的小数部分必须打印多少个数字? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. 必须至少有一个数字来表示小数部分,并且除此以外,还需要与唯一的双精度类型的值唯一地区分参数值的数字一样多,但也只有尽可能多的数字。

This is because the double number has no notion of "decimal precision". 这是因为double精度数没有“十进制精度”的概念。 It is a binary number with fixed binary precision (number of binary digits after the binary point). 它是与固定的二进制精度(在二进制小数点后的二进制数字数)的二进制数。

Just use BigDecimal instead of Double like this: 像这样使用BigDecimal而不是Double:

BigDecimal houndred = new BigDecimal("100.00").setScale(2, BigDecimal.ROUND_HALF_UP);

BigDecimal does not loose precision at all. BigDecimal完全不会降低精度。 Additionally you can set scale, precision and rounding mode as you prefer. 另外,您可以根据需要设置比例,精度和舍入模式。

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

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