Member-only story

DBigDecimal Usage Details

Beck Moulton
2 min readApr 6, 2023

--

Java API class BigDecimal provided in the java.math package is used to perform exact operations on numbers with more than 16 significant bits. The double-precision floating-point variable double can handle 16 significant bits, but in practical applications, it may be necessary to calculate and process larger or smaller numbers.

BigDecimal creates objects, so we cannot use traditional arithmetic operators such as +、-、*、/ to perform mathematical operations directly on their objects, but must call their corresponding methods. The parameters in the method must also be BigDecimal objects. Constructors are special methods of classes designed to create objects, especially objects with parameters.

# Detail 1

Use case

BigDecimal a =new BigDecimal(0.1);
System.out.println("a values is:"+a);
System.out.println("=====================");
BigDecimal b =new BigDecimal("0.1");
System.out.println("b values is:"+b);

Implementation results

a values is:0.1000000000000000055511151231257827021181583404541015625
=====================
b values is:0.1

Phenomenon analysis:

  1. The result of a constructor with parameter type double is somewhat unpredictable. One might think that writing newBigDecimal (0.1) in the Java creates a BigDecimal that is exactly equal to 0.1 (non-scale value 1, which has a scale of 1), but it is actually equal to 1000000000000000055511151231257827021181583404541015625. This is because…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet