Solution to the exception of double type operation result in Java

Question:

When two double type values are operated, sometimes the result value is abnormal. For example:

Output:

39.989999999999995 0.33999999999999997 3.3000000000000003 0.12300000000000001

resolvent:

The simple floating-point types float and double in Java cannot operate because they are normal in most cases, but the problems shown above occasionally occur. In fact, this problem is not a Java bug, because the computer itself is binary, and the floating point number is actually only an approximate value. Therefore, when converting from binary to decimal floating point number, the accuracy is easy to be lost, resulting in the decline of accuracy.

To ensure accuracy, you need to use the BigDecimal class, and you can't directly convert from double to BigDecimal. You need to convert double to string and then to BigDecimal. That is, the BigDecimal (double VAL) method cannot be used, and you will find no effect. To use the BigDecimal (string VAL) method. Specific examples are as follows.

Four operation examples of double type:

1. Add

2. Subtraction

3. Multiply

4. Divide

When the scale parameter is not divisible, specify the precision.

The above solution to the abnormal operation result of double type in Java is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>