Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal.ZERO vs. new BigDecimal(0). Which to use and why?

I was wondering if these two are the same. Can anyone verify? (I am trying to replace the 1st with the 2nd)

BigDecimal totalCurrentSales = new BigDecimal(0); 

and

BigDecimal totalCurrentSales = BigDecimal.ZERO; 

The reason I ask is that it is improper to declare it the first way since you are not supposed to create instances of already existing BigInteger and BigDecimal (ZERO, ONE, TEN). So I was wondering if I could say it the second way and it still be considered creating an instance. Instead of me having to create a variable zero or something that is equal to BigDecimal.ZERO. Or are there any other ways?

I tried

BigDecimal totalCurrentSales = new BigDecimal(BigDecimal.ZERO); 

but eclipse wasn't too happy.

like image 716
erp Avatar asked Oct 14 '14 15:10

erp


People also ask

Why should we use BigDecimal?

The BigDecimal class provides operations on double numbers for arithmetic, scale handling, rounding, comparison, format conversion and hashing. It can handle very large and very small floating point numbers with great precision but compensating with the time complexity a bit.

How do you check if BigDecimal is zero or not?

Using the compareTo Method Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. Therefore, we can check BigDecimal. ZERO. compareTo(givenBdNumber) == 0 to decide if givenBdNumber has the value zero.

What is the advantage that we get from using BigDecimal compared to a double?

A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001 ) could result in the 0.001 being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen.


1 Answers

Mathematically, they're the same. Plus, since BigDecimals are immutable, you don't need to worry about creating new instances to do new calculations. As soon as you perform some operation on your totalCurrentSales instance, you'll actually be creating a new BigDecimal and reassigning the totalCurrentSales reference to the new value.

From a instantiation perspective, they're not necessarily exactly the same. In the OpenJDK 6b14 implementation, for example, BigDecimal.ZERO is created by invoking the private new BigDecimal(BigInteger, long, int) constructor with values BigInteger.ZERO, 0, and 0.

From a code quality perspective, using BigDecimal.ZERO is preferable to new BigDecimal(0) as you avoid the extra instantiation and having a literal in your code.

like image 97
bdkosher Avatar answered Oct 17 '22 21:10

bdkosher