Home > Java > javaTutorial > How to use BigDecimal to perform mathematical operations in java

How to use BigDecimal to perform mathematical operations in java

WBOY
Release: 2023-05-03 09:31:14
forward
1302 people have browsed it

1. When BigDecimal is added, subtracted, or multiplied, the precision will not be lost. However, when doing division, there may be situations where it cannot be divided. In this case, the precision and how to truncate must be specified.

   import java.math.BigDecimal;
   import java.math.RoundingMode;
   
   public class Demo {
    public static void main(String[] args) {
     BigDecimal d1 = new BigDecimal("123.456");
     BigDecimal d2 = new BigDecimal("23.456789");
     BigDecimal d3 = d1.divide(d2, 10, RoundingMode.HALF_UP); // 保留10位小数并四舍五入
     BigDecimal d4 = d1.divide(d2); // 报错:ArithmeticException,因为除不尽
    }
   }
Copy after login

2. You can divide BigDecimal and find the remainder at the same time.

   import java.math.BigDecimal;
   public class Demo {
    public static void main(String[] args) {
     BigDecimal n = new BigDecimal("22.444");
           BigDecimal m = new BigDecimal("0.23");
           BigDecimal[] dr = n.divideAndRemainder(m);
           System.out.println(dr[0]); // 97.0
           System.out.println(dr[1]); // 0.134
    }
   }
Copy after login

The above is the detailed content of How to use BigDecimal to perform mathematical operations in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template