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

How to summarize the use of BigDecimal class and int and Integer in Java

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

Share

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

This article introduces how to summarize the use of BigDecimal classes and int and Integer in Java, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Preface

We all know that floating-point variables will lose precision when calculating. The following code:

System.out.println, output: 0.06000000000000050.580000000001401.4999999999941.2329999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999

You can see that the problem of loss of precision occurs when floating-point operations are performed in Java. Then if we calculate the price of goods, there will be problems. It is very likely that we have 0.06 yuan in hand, but we are unable to buy a commodity of 0.05 yuan and 0.01 yuan. Because as shown above, the sum of the two of them is 0.0600000000000005. This is undoubtedly a very serious problem, especially when the concurrency of e-commerce websites goes up, the problem will be huge. It may result in the inability to place an order or a problem with the reconciliation. So then we can use the BigDecimal class in Java to solve this kind of problem.

The precision of float in Java is 6-7 significant digits. The precision of double is 15-16 bits.

API

The method describes the addition of the values in the add (BigDecimal) BigDecimal object and returns the object. The value in the subtract (BigDecimal) BigDecimal object is subtracted and the object is returned. Multiply the values in the multiply (BigDecimal) BigDecimal object and return this object. Divides the values in the pide (BigDecimal) BigDecimal object and returns this object. ToString () converts the numeric value of the BigDecimal object to a string. DoubleValue () returns the value in the BigDecimal object as a double. FloatValue () returns the value in the BigDecimal object as a single precision number. LongValue () returns the value in the BigDecimal object as a long integer. IntValue () returns the value in the BigDecimal object as an integer.

BigDecimal precision is also lost.

When we use BigDecimal, it makes sense to use its BigDecimal (String) constructor to create objects. Others, such as BigDecimal b = new BigDecimal (1), still have the problem of loss of precision. The code is as follows:

BigDecimal a = new BigDecimal (1.01); BigDecimal b = new BigDecimal (1.02); BigDecimal c = new BigDecimal ("1.01"); BigDecimal d = new BigDecimal ("1.02"); System.out.println (a.add (b)); System.out.println (c.add (d)); output: 2.03000000000026645259100375697016716001768752.03

It can be seen that the loss of precision BigDecimal is even more excessive. However, variables that use Bigdecimal's BigDecimal (String) constructor do not have this problem when performing operations. The reason is that there are all the principles of computer composition, and their coding determines such results. Long can store exactly 19 digits, while double can only prepare to store 16 digits. Double can store more than 16 digits because of its exp bits, but at the expense of low bit imprecision. If you need accurate storage of more than 19 digits, you must save it with BigInteger, at the expense of some performance. So when we generally use BigDecimal to solve the problem of loss of precision in business operations, we must use it to construct a type constructor with a parameter of String when declaring a BigDecimal object.

At the same time, this principle is also mentioned in Effective Java and MySQL. Float and double can only be used for scientific and engineering calculations. We will use BigDecimal in business operations.

Correct use of BigDecimal

BigDecimal BigDecimal (double d); / / not allowed

BigDecimal BigDecimal (String s); / / commonly used, recommended

Static BigDecimal valueOf (double d); / / commonly used, recommended

The reasons are

The construction method of double parameter is not allowed! Because it cannot get the corresponding value exactly; the String constructor is completely predictable: writing new BigDecimal ("0.1") creates a BigDecimal, which is exactly equal to the expected 0.1; therefore, it is usually recommended to give priority to the String constructor; the static method valueOf (doubleval) internal implementation is still to convert the double type to String type; this is usually the preferred method to convert double (or float) to BigDecimal

Size comparison of BigDecimal

Example: a.compareTo (b)

< 0 compareTo 返回: -1,0,1 -1 小于 0 等于 1 大于 BigDecimal 的小数点后位数 BigDecimal c = new BigDecimal("2.224667").setScale(2, BigDecimal.ROUND_UP);System.out.println(c);//2.23 跟上面相反,进位处理----------ROUND_CEILING 天花板(向上):正数进位向上,负数舍位向上BigDecimal f = new BigDecimal("2.224667").setScale(2, BigDecimal.ROUND_CEILING);System.out.println(f);//2.23 如果是正数,相当于BigDecimal.ROUND_UPBigDecimal g = new BigDecimal("-2.225667").setScale(2, BigDecimal.ROUND_CEILING);System.out.println(g);//-2.22 如果是负数,相当于BigDecimal.ROUND_DOWN----------ROUND_FLOOR 地板(向下):正数舍位向下,负数进位向下BigDecimal h = new BigDecimal("2.225667").setScale(2, BigDecimal.ROUND_FLOOR);System.out.println(h);//2.22 如果是正数,相当于BigDecimal.ROUND_DOWNBigDecimal i = new BigDecimal("-2.224667").setScale(2, BigDecimal.ROUND_FLOOR);----------ROUND_HALF_UPBigDecimal d = new BigDecimal("2.225").setScale(2, BigDecimal.ROUND_HALF_UP);System.out.println("ROUND_HALF_UP"+d); //2.23 四舍五入(若舍弃部分>

= .5, rounding up)-ROUND_HALF_DOWNBigDecimal e = new BigDecimal ("2.225"). SetScale (2, BigDecimal.ROUND_HALF_DOWN); System.out.println ("ROUND_HALF_DOWN" + e); / / 2.22 rounding (rounding if the discarded part > .5)-

The difference between int and Integer

Int is one of the eight primitive types provided by java, java provides a wrapper class for each primitive type, and Integer is a wrapper class for int. The default value of int is 0, while the default value of Integer is null; int and Integer (no matter whether new or not), it is true, because Integer will be automatically unboxed to int and then compared; Integer is a reference type, compare two objects with = =, in fact, compare their memory addresses, so different Integer objects must be different; but for Integer iComplete java will interpret it as Integer i=Integer.valueOf (); However, the Integer class caches integers between [- 128127], so for Integer i1 to 127; and Integer i2 to 127;, i1==i2, because the two objects point to the same memory unit. For Integer i1: 128; and Integer i2: 128;, i1==i2 is false.

Their respective application scenarios

The default value of Integer is null, which can distinguish between unassigned and 0 values. For example, students who did not take the exam and students with test scores of 0 have more addition, subtraction, multiplication, division and comparison operations, and Integer is recommended in the int container. For PO entity classes, the property should be defined as Integer if the DBRint field allows null. Of course, if the system limits that the int field in db does not allow null values, you can also consider defining the property as int. For enumerated types defined in the application, if the value is an integer, it is best defined as int. Integer provides a series of data members and operations, such as Integer.MAX_VALUE,Integer.valueOf (), Integer.compare (), and compareTo (), for ease of comparison with other int values or Integer values, but it is generally used less. It is recommended that you generally use the int type to save unpacking on the one hand and avoid the bug that may be brought about by data comparison on the other hand.

On how to summarize the BigDecimal class in Java and int, Integer use to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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: 230

*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