Simple use of the BigDecimal class in Java

  • 2020-04-01 03:28:03
  • OfStack

This article is an example of a simple use of the BigDecimal class in Java. It is a useful tip in Java programming. Specific usage analysis is as follows:

In general, when it comes to commercial computing in Java, we all know that you can't use floats and doubles because they don't compute exactly. But Java's designers have provided programmers with a useful class called BigDecimal, which complements the inability of float and double classes to perform precise calculations. The BigDecimal class is under the java.maths class package. First let's look at how to construct a BigDecimal object. It has many constructors, so let's pick the two most commonly used to demonstrate this: 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:




That is, a constructor that takes a double as an argument cannot exactly construct a BigDecimal object and needs to specify a context of its own, that is, specify the exact bit. A constructor passed in with a String object as an argument can precisely construct a BigDecimal object. Look at the following code:


import java.math.*;
public class TestBigDecimal {
  public static void main(String args[]){
    BigDecimal bd = new BigDecimal("10.123");
    BigDecimal bd1 = new BigDecimal(10.123);
    System.out.println(bd +"/n"+ bd1);
  }
}

Output after operation:

10.123
10.1229999999999993320898283855058252811431884765625

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

In addition, many people ask how to convert primitive types such as int, float, double, long, and BigDecimal objects to each other. Is simple:

The basic types are converted to corresponding BigDecimal objects by constructors, and the BigDecimal class provides methods such as intValue(), floatValue(), doubleValue(), and longValue() to convert BigDecimal objects to corresponding values.

As for how BigDecimal is calculated, I simply wrote down how to calculate BigDecimal using a question post from a person in the forum. The title is: li bai has no matter to walk in the street, carry pot to buy wine. Meet the inn to add one times, see the flower to drink a bucket, five meet the flower and the inn, drink the wine in the kettle, try to ask li bai in the original how much bucket of wine?

So this is going to go backwards and backwards to get the volume of the original wine.


import java.math.*;
public class Libai {
  public static void main(String args[]){
    BigDecimal volumn = new BigDecimal("0");
    for (int i=0; i<5; i++){      
      volumn = volumn.add(new BigDecimal("1"));
      volumn = volumn.divide(new BigDecimal("2"));
    }
    System.out.print(volumn);
  }
}

Operation results:

0.96875

I hope this article will be helpful to your Java programming study.


Related articles: