Why does New bigdecimal (0.1) and new bigdecimal ("0.1") differ?
Source: Internet
Author: User
When bigdecimal is used for comparison, we will find that new bigdecimal (0.1) and new bigdecimal ("0.1") are not equal. Later we checked the API and found that for new bigdecimal (double var) it is described as follows:
The results of this constructor are unpredictable. Some people may think that the bigdecimal created by writing new bigdecimal (0.1) in Java is exactly equal to 0.1 (the non-standard degree value 1, its scale is 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be accurately expressed as a double (or in this case, it cannot be expressed as any binary decimal with a limited length ). In this way, the value passed into the constructor is not exactly equal to 0.1 (although it is equal to this value on the surface ).
On the other hand, the string constructor is completely predictable: writing new bigdecimal ("0.1") will create a bigdecimal, Which is exactly equal to the expected 0.1. Therefore, we recommend that you use the string constructor first.
When double must be used as the source of bigdecimal, please note that this constructor provides an accurate conversion; it does not provide the same result as the following operation: Use double first. tostring (double) method, and then use the bigdecimal (string) constructor to convert double to string. To obtain this result, use the static valueof (double) method.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.