A tentative study of Java BigDecimal

Source: Internet
Author: User

Update Time: 2016-03-17

First, Introduction

"Effactive Java" has such a description: float and double type of the main design objectives for scientific calculations and engineering calculations. They perform binary floating-point operations, which are designed to provide more accurate, fast approximation calculations over a wide range of values. However, they do not provide completely accurate results, so they should not be used in situations where precise results are required. However, currency calculations often require accurate results, which can be used int , long or BigDecimal .

Second, non-variability

BigDecimalis an immutable class, each operation (subtraction, etc.) returns a new object, as an example of an addition operation:

BigDecimal a =new BigDecimal("1.22");System.out.println("construct with a String value: " + a);BigDecimal b =new BigDecimal("2.22");a.add(b);System.out.println("a plus b is : " + a);

It is easy to assume that the output will be:

construct with a String value: 1.22a plus b is :3.44

But actually a plus B is:1.22

Because BigDecimal it is immutable (immutable), in every step of the operation, will produce a new object, so a.add(b) although the addition operation, but a does not save the value after the operation, the correct usage should be a=a.add(b); reduced multiplication operation is the same as return a new BigDecimalobject.

Iii. Constructors and ValueOf methods

First look at the following section of code:

// use constructor BigDecimal(double) BigDecimal aDouble =new BigDecimal(1.22);System.out.println("construct with a double value: " + aDouble);// use constructor BigDecimal(String)BigDecimal aString = new BigDecimal("1.22");System.out.println("construct with a String value: " + aString);// use constructor BigDecimal.valueOf(double)BigDecimal aValue = BigDecimal.valueOf(1.22);System.out.println("use valueOf method: " + aValue);

What do you think the output will be? If you think the first one will output 1.22, then congratulations on your wrong answer, the output is as follows:

construct with a double value: 1.2199999999999999733546474089962430298328399658203125construct with a String value: 1.22use valueOf method: 1.22

Why is that? Javadoc for a BigDecimal(double) very detailed description:

1. The result of the construction method with the parameter type is double unpredictable. One might think that the value created in Java is new BigDecimal(0.1) BigDecimal exactly equal to 0.1 (non-scale value 1, with a scale of 1), But it's actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be accurately represented as double (or for that case, it cannot be represented as any finite-length binary decimal). This way, the value passed into the construction method does not exactly equal 0.1 (although it is on the surface equal to the value).

2, on the other hand, the String construction method is completely predictable: new BigDecimal("0.1") A BigDecimal is created, and its value is exactly equal to the desired 0.1. Therefore, in comparison, it is generally recommended that the String construction method be preferred .

3. When double the source must be used BigDecimal , note that this construction method provides an exact conversion; it does not provide the same result: the first Use Double.toString(double) method is double converted to String , and then the BigDecimal(String) construction method is used. To get the result, use the static valueOf(double) method.

BigDecimal.valueOf(double)Use the Double.toString(double) normalized string representation provided by the method double (canonical string representation) to double convert to BigDecimal . This is also a more recommended way.

BigDecimal.valueOf(double)There is also an overloaded method BigDecimal.valueOf(long) that caches internally for some common values (0 to ten) BigDecimal , and if the value of the parameter passed is [0, 10], this method directly returns the corresponding object in the cache BigDecimal .

Iv. method of equals

BigDecimal.equalsThere is a problem with the method. Use only if you are sure that the value of the comparison has the same scale. Therefore, when you check for equality, note that BigDecimal there is a scale for equality comparisons. compareTothe scale is ignored by the method.

See the following test code:

// 打印falseSystem.out.println(new BigDecimal("0.0").equals(new BigDecimal("0.00")));// 打印falseSystem.out.println(new BigDecimal("0.0").hashCode() == (new BigDecimal("0.00")).hashCode());// 打印0System.out.println(new BigDecimal("0.0").compareTo(new BigDecimal("0.00")));
V. Use SCALE for Division

BigDecimalThere is no limit to the precision of the object. If the result cannot be terminated, the divide method will be thrown ArithmeticException , such as 1/3 = 0.33333 .... Therefore, it is highly recommended to use overloaded methods divide(BigDecimal d, int scale, int roundMode) to specify scale and rounding patterns to avoid the above exceptions.

About rounding patterns are commonly used BigDecimal.ROUND_HALF_UP , that is, rounding.

Vi. Summary

1, commercial computing (requires accurate results) when used BigDecimal .

2, using the parameter type String of the constructor, will be converted to the double BigDecimal time BigDecimal.valueOf(double) , do the division operation using overloaded methods divide(BigDecimal d, int scale, int roundMode) .

3, BigDecimal is immutable (immutable), in each step of the operation, will produce a new object, so in doing subtraction operation, you must save the value of the operation.

4, try compareTo BigDecimal to use the method to compare the size of two objects.

A tentative study of Java BigDecimal

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.