Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Java calculates exactly how the BigDecimal class is used

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "Java accurate calculation of how to use the BigDecimal class", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "Java accurately calculates how to use the BigDecimal class".

Introduction

The main design goals of the float and double types are for scientific and engineering calculations. They perform binary floating-point operations, which are carefully designed to provide more accurate and fast approximate calculations over a wide range of values. However, they do not provide completely accurate results, so they should not be used in situations where accurate results are required. However, business calculations often require accurate results, so BigDecimal comes in handy.

Take a look at the following code first

Public static void main (String [] args) {System.out.println (0 2 + 0 1); System.out.println (0 3-0 1); System.out.println (0 2 * 0 1); System.out.println (0 3 / 0 1);}

The running result is as follows

You think you read it wrong, but it turns out like this. What is the problem? The reason is that our computer is binary. There is no way for floating point numbers to be accurately represented in binary. Our CPU representation of floating-point numbers consists of two parts: exponents and Mantissa, which generally lose a certain degree of accuracy, and some floating-point operations also produce certain errors. For example, the binary representation of 2.4 is not the exact 2.4. On the contrary, the closest binary representation is 2.3999999999999999. The value of a floating point number is actually calculated by a specific mathematical formula.

In fact, the float of java can only be used for scientific calculation or engineering calculation. In most business calculations, the java.math.BigDecimal class is generally used for accurate calculation.

BigDecimal construction method

1.public BigDecimal (doubleval) converts the double representation to BigDecimal * not recommended

2.public BigDecimal (int val) converts the int representation to BigDecimal

3.public BigDecimal (String val) converts the String representation to BigDecimal

Why not recommend the first construction method? Let's take a look at examples.

Public static void main (String [] args) {BigDecimal bigDecimal= new BigDecimal (2); BigDecimal bDouble= new BigDecimal (2.3); BigDecimal bString= new BigDecimal ("2.3"); System.out.println ("bigDecimal=" + bigDecimal); System.out.println ("bDouble=" + bDouble); System.out.println ("bString=" + bString);}

The running result is as follows

Why did this happen?

Description of JDK:

1. The result of the construction method whose parameter type is double has some unpredictability. One might think that the BigDecimal created by writing newBigDecimal (0.1) in Java is exactly equal to 0.1 (a non-scalar value of 1 with a scale of 1), but it is actually equal to 0.10000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be accurately represented as double (or, in this case, as any finite length binary decimal). In this way, the value passed into the constructor is not exactly equal to 0.1 (although ostensibly equal to that value).

2. On the other hand, the String constructor is completely predictable: writing newBigDecimal ("0.1") creates a BigDecimal that is exactly equal to the expected 0.1. Therefore, by comparison, it is generally recommended that the String construction method be preferred.

When double must be used as the source of BigDecimal, use Double.toString (double) to convert to String, and then use the String constructor, or use BigDecimal's static method valueOf, as follows

Public static void main (String [] args) {BigDecimal bDouble1= BigDecimal.valueOf (2.3); BigDecimal bDouble2= new BigDecimal (Double.toString (2.3)); System.out.println ("bDouble1=" + bDouble1); System.out.println ("bDouble2=" + bDouble2);}

The results are as follows

BigDecimal addition, subtraction, multiplication and division

For the commonly used addition, subtraction, multiplication, division, BigDecimal classes provide the corresponding member methods.

Public BigDecimal add (BigDecimal value); / / addition public BigDecimal subtract (BigDecimal value); / / subtraction public BigDecimal multiply (BigDecimal value); / / multiplication public BigDecimal divide (BigDecimal value); / / division

The approximate usage is as follows

Public static void main (String [] args) {BigDecimal a = new BigDecimal; BigDecimal b = new BigDecimal ("1.5"); System.out.println ("a + b =" + a.add (b)); System.out.println ("a-b =" + a.subtract (b)); System.out.println ("a * b =" + a.multiply (b)) System.out.println ("a / b =" + a.divide (b));}

Running result

One thing to note here is the division operation divide.

BigDecimal division may not be divisible, such as 4.5 java.lang.ArithmeticException 1.3, which will result in an error error: Non-terminating decimal expansion; no exact representable decimal result.

In fact, the divide method can pass three parameters.

Public BigDecimal divide (BigDecimal divisor, int scale, int roundingMode)

The first parameter represents the divisor, and the second parameter represents the number of reserved places after the decimal point.

The third parameter represents the rounding mode, which is used only when dividing or rounding. There are several types of rounding modes

ROUND_CEILING / / rounding in positive infinity ROUND_DOWN / / rounding in zero direction ROUND_FLOOR / / rounding in negative infinity ROUND_HALF_DOWN / / rounding the nearest side unless both sides are equal, if so, rounding down, for example, 1.55 keeping a decimal place resulting in 1.5ROUND_HALF_EVEN / / rounding the nearest side Unless both sides are equal, if so, if the reserved digits are odd, use ROUND_HALF_UP, if it is even, use ROUND_HALF_DOWNROUND_HALF_UP / / to the nearest side, unless the two sides are equal, if so, round up, 1.55 leave one decimal place to 1.6ROUND_UNNECESSARY / / the result is accurate There is no need for rounding mode ROUND_UP / / rounding away from 0

According to their respective needs, you can pass in the appropriate third parameter. Rounded up with ROUND_HALF_UP

SetScale methods are available for truncating and rounding BigDecimal, for example:

Public static void main (String [] args) {BigDecimal a = new BigDecimal ("4.5635"); a = a.setScale (3, RoundingMode.HALF_UP); / / keep 3 decimal places and round System.out.println (a);}

In fact, subtraction, multiplication and division will eventually return a new BigDecimal object, because both BigInteger and BigDecimal are immutable, and a new object will be generated at each step of the operation.

Public static void main (String [] args) {BigDecimal a = new BigDecimal; BigDecimal b = new BigDecimal ("1.5"); a.add (b); System.out.println (a); / / output 4.5. The addition, subtraction, multiplication and division method will return a new BigDecimal object, the original a unchanged} so far, I believe you have a deeper understanding of "Java accurately calculate how to use the BigDecimal class", you might as well come to the actual operation! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report