Simple usage of BigDecimal class in Java

This example describes the simple usage of BigDecimal class in Java. It is a very practical skill in Java programming. It is shared for your reference. The specific usage analysis is as follows:

Generally speaking, when it comes to Business Computing in Java, we all know that float and double cannot be used because they cannot perform accurate calculations. However, the designer of Java provides programmers with a very useful class BigDecimal, which can improve the defect that the float and double classes cannot calculate accurately. The BigDecimal class is located in Java Under the math class package. First, let's look at how to construct a BigDecimal object. It has many constructors. Here we choose the two most commonly used constructors to demonstrate: one is BigDecimal (double VAL) and the other is BigDecimal (string STR). The two don't look very different, but as the API description says:

In other words, using the constructor with double as a parameter cannot accurately construct a BigDecimal object. You need to specify a context environment, that is, specify the exact bit. The constructor passed in using the string object as a parameter can accurately construct a BigDecimal object. See the following code:

Output after operation:

10.123 10.1229999999999993320898283855058252811431884765625

Therefore, when we choose the constructor, it depends on the specific requirements.

In addition, many people will ask how to convert basic types such as int, float, double, long, and BigDecimal objects to each other. It's simple:

The basic type is converted to the corresponding BigDecimal object through the constructor, and the BigDecimal class provides methods such as intvalue(), floatvalue(), doublevalue(), longvalue() to convert the BigDecimal object to the corresponding value.

About how BigDecimal is calculated, I take a question post from a person in the forum as an example to simply write the operation method of BigDecimal. The title is: Li Bai walks down the street without anything, carrying a pot to buy wine. When you meet the shop, double it. When you see the flowers, drink a bucket. When you meet the flowers and the shop, drink all the wine in the pot. How many buckets of wine are there in Li Bai's pot?

This problem should be pushed back and forward, and the inverse operation should be carried out to finally get the volume of the original wine.

Operation results:

zero point nine six eight seven five

I hope this article will help you learn java programming.

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