Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use BigDecimal to do Mathematical Operation in java

Shulou Source: shulou.com Published: 2022-05-31 10:48:27 09月29日 Update

This article mainly explains "how to use BigDecimal to do mathematical operations in java". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use BigDecimal to do mathematical operations in java".

1. When BigDecimal is doing addition, subtraction and multiplication, the precision will not be lost, but when doing division, there is a situation that cannot be divided, so it is necessary to specify the precision and how to truncate.

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); / / keep 10 decimal places and round BigDecimal D4 = d1.divide (D2) / / error report: ArithmeticException, because it can not be divided}}

2. You can find the rest while dividing BigDecimal.

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}} Thank you for your reading. The above is the content of "how to do mathematical operations with BigDecimal in java". After the study of this article, I believe you have a deeper understanding of how to do mathematical operations with BigDecimal in java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Mathematics operation learning content situation precision division rounding at the same time decimal that is ideas articles more knowledge knowledge points articles follow questions give up Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker NVidia Apple OPPO Reno Xiaomi