Using BigDecimal in Java to perform operations such as addition, subtraction, multiplication, and division on string values

Directory of series articles

SpringBoot + Vue3 implements login verification code function
Java implements sending emails (automatically sending emails regularly)
Use Redis from another angle to solve the problem of cross-domain access Session
Redis cache penetration, breakdown, avalanche problems and solutions
Use of Spring Cache – Quick Start
List<HashMap<String,String>>implement custom string sorting (key sorting, Value sorting)

For more articles in this series, please check my homepage

Article directory

  • Table of Contents of Series Articles
  • Preface
  • 1. Introduction to BigDecimal
  • 2. Methods for calling addition, subtraction, multiplication and division operations
    • 2.1 Addition add()
    • 2.2 Subtraction subtract()
    • 2.3 Multiplication multiply()
    • 2.4 Division divide()
  • 3. Other operations
    • 3.1 Absolute value abs()
    • 3.2 Compare size compareTo()
  • Summarize

Foreword

In actual development, when the front-end passes a value of String type to the back-end, when we want to perform addition, subtraction, multiplication, and division on these String type values, such as int type operations, we will use BigDecimal to perform the operation. . But everyone will definitely say that if we force the type to be converted to int type, wouldn’t it be more convenient to operate? Why do you still need to learn this? Because of the upper limit of the int type, what is the specific upper limit? I believe that everyone who has written high-precision addition and subtraction algorithm questions will understand the shortcomings of the int type. So we need to use it when involving high-precision operations of addition, subtraction, multiplication and division. Please see the following content for how to use it~

1. Introduction to BigDecimal

The API class BigDecimal provided by Java in the java.math package is used to perform precise operations on numbers with more than 16 significant digits . Double precision floating point variable double can handle 16 significant numbers. In practical applications, it is necessary to perform operations and processing on larger or smaller numbers. Float and double can only be used for scientific calculations or engineering calculations. In commercial calculations, java.math.BigDecimal should be used. What BigDecimal creates is an object. We cannot use traditional arithmetic operators such as +, -, *, / to directly perform mathematical operations on its objects, but must call its corresponding methods. The parameters in the method must also be BigDecimal objects. Constructors are special methods of a class that are used to create objects, especially objects with parameters.

To put it simply, BigDecimal is used when operating and processing larger or smaller numbers. When using it, you need to call the corresponding method to complete the corresponding operation.

2. Methods called for addition, subtraction, multiplication and division operations

2.1 Addition add()

Addition requires calling the add method, just use new. The code is as follows, a.add(b) means a + b:
Note that the value is converted to String type after processing

 //Addition add
        System.out.println("**********Addition******************");
        BigDecimal a = new BigDecimal("1.01");
        BigDecimal b = new BigDecimal("2.01");
        String result = a.add(b).toString();
        System.out.println("Addition: use of add ----- a + b = " + a.toString() + " + " + b.toString() + " = " + result);

Operation rendering:

2.2 Subtraction subtract()

Subtraction requires calling the subtract method. The code is as follows: a1.subtract(b1) means a1-b1
Note that the value is converted to String type after processing

 System.out.println("**********Subtraction****************");
        BigDecimal a1 = new BigDecimal("2.02");
        BigDecimal b1 = new BigDecimal("1.01");
        String result1 = a1.subtract(b1).toString();
        System.out.println("Subtraction: use of subtract ----- a1 - b1 = " + a1.toString() + "-" + b1.toString() + " = " + result1);

Operation rendering:

2.3 Multiplication multiply()

Multiplication requires calling the multiply method. The code is as follows:a2.multiply(b2) means a2b2*
Note that the value is converted to String type after processing

 System.out.println("************Multiplication****************");
        //Multiplication multiply
        BigDecimal a2 = new BigDecimal("2.02");
        BigDecimal b2 = new BigDecimal("1.01");
        String result2 = a1.multiply(b1).toString();
        System.out.println("Multiplication (retain all decimal places): use of multiply ----- a2 * b2 = " + a2.toString() + "*" + b2.toString() + " = " + result2 );

        String result3 = a1.multiply(b1).setScale(2, RoundingMode.HALF_UP).toString();
        System.out.println("Multiplication (retaining 2 decimal places): Use multiply in combination with setScale----- a2 * b2 = " + a2.toString() + "*" + b2.toString() + " = " + result3);

Run the rendering. You need to call the setScale method to retain 2 decimal places. The ‘2’ in the code represents 2 decimal places:

2.4 Division divide()

Division requires calling the divide method. The code is as follows: a3.divide(b3) means a3/b3
Note that after processing, the value must be converted to String type, and the number of decimal places must be specified! ! !

 System.out.println("**********divide****************");
        BigDecimal a3 = new BigDecimal("2.03");
        BigDecimal b3 = new BigDecimal("1.01");
        //Note that if the decimal place after the output is too large, an error will be reported, such as 5/3=1.666666666666~, an error will be reported, generally not used
// String result4 = a3.divide(b3).toString();
// System.out.println("Division (retain all decimal places): use of divide----- a3 / b3 = " + a3.toString() + "/" + b3.toString() + " = " + result4);

        //So this way of writing with 2 decimal places is generally used directly.
        String result5 = a3.divide(b3,2,RoundingMode.HALF_UP).toString();
        System.out.println("Division (keep 2 decimal places): use of divide----- a3 / b3 = " + a3.toString() + "/" + b3.toString() + " = " + result5 );

When running the rendering,note that the number of decimal places must be specified here. If you do not specify a recurring decimal, an error will be reported:

3. Other operations

3.1 Absolute value abs()

Absolute values require calling the abs method. The code is as follows: a4.abs() means \a4\
Note that the value is converted to String type after processing

 //1.Absolute value
        BigDecimal a4 = new BigDecimal("-1.2");
        BigDecimal result6 = a4.abs();
        System.out.println("Get absolute value: use of abs-----" + "|" + a4 + "|" + " = " + result6);

Operation rendering:

3.2 Compare size compareTo()

To compare sizes, you need to call the compareTo method. The code is as follows: a5.compareTo(b5) means a5>b5?
Note that after processing, the value is converted to String type. If it is greater than 1, if it is equal to 0, if it is less than 1, it will return -1

 //2. Determine the size
        BigDecimal a5 = new BigDecimal("1.3");
        BigDecimal b5 = new BigDecimal("1.2");
        //Is a5 greater than b5
        int i = a5.compareTo(b5); //(less than returns -1) (equal to returns 0) (greater than returns 1)
        String result7="";
        if(i == -1){<!-- -->
            result7 = "less than";
        }
        if(i == 0){<!-- -->
            result7 = "equal to";
        }
        if(i == 1){<!-- -->
            result7 = "greater than";
        }
        System.out.println("Compare size: use of compareTo ----- whether a5 is greater than b5 result = " + result7 + " i = " + i);

Operation rendering:

Summary

The above is a code and rendering demonstration of the commonly used methods of BigDecimal. I believe everyone can use it to perform the above operations on values after seeing it here! I believe everyone has a certain understanding and knowledge of BigDecimal! If you encounter any problems, you can communicate in the comment area, and we can learn and improve together~