BigDecimal is used for precise operation in Java

First, let's look at the following code example:

The operation results are as follows.

zero point zero six nine nine nine nine nine nine nine nine nine nine nine nine nine nine nine

zero point five eight zero zero zero zero zero zero zero zero zero zero zero zero zero one

four hundred and one point four nine nine nine nine nine nine nine nine nine nine nine nine four

zero point three zero three one zero zero zero zero zero zero zero zero zero zero zero zero four

You think you're wrong, but that's the result. What's the problem? The reason is that our computer is binary. There is no way to accurately represent floating-point numbers in binary. Our CPU representation of floating-point numbers consists of two parts: exponent and mantissa. Generally, such representation methods will lose certain accuracy, and some floating-point operations will also produce certain errors. For example, the binary representation of 2.4 is not exactly 2.4. Instead, the closest binary representation is 2.39999999999999999. The value of a floating-point number is actually calculated by a specific mathematical formula.

In fact, Java's float can only be used for scientific computing or engineering computing. In most commercial computing, Java is generally used math. BigDecimal class to perform exact calculations.

When using BigDecimal class for calculation, it is mainly divided into the following steps:

1. Build BigDecimal objects with float or double variables.

2. Perform arithmetic operations by calling BigDecimal's addition, subtraction, multiplication, division and other corresponding methods.

3. Convert BigDecimal objects to float, double, int and other types.

Generally speaking, you can use the construction method of BigDecimal or the valueof () method of static method to build basic type variables into BigDecimal objects.

BigDecimal class provides corresponding member methods for common addition, subtraction, multiplication and division.

After the corresponding calculation, we may need to convert the BigDecimal object into a variable of the corresponding basic data type. We can use methods such as floatvalue(), doublevalue().

The following is a tool class that provides addition, subtraction, multiplication and division operations.

The above is what Xiaobian introduced to you about the use of BigDecimal for accurate calculation in Java. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

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
分享
二维码
< <上一篇
下一篇>>