0

I found some code in legacy software and i was interested in knowing which provides better precision, as it currently is where it takes the double and calculates on them:

double doubleNum = (Math.round(55.88d * 100) - Math.round(2.33d * 100));

second option

BigDecimal bnv = BigDecimal.valueOf(55.88);
BigDecimal bsv = BigDecimal.valueOf(2.33);

System.out.println(bnv.subtract(bsv).setScale(2));

Both produce the same output, my understanding was that using bigdecimal ensures that is more precise. But there could be loss when converting double to BigDecimal

Also the first option there is possible loss when casting..

I always use BigDecimal, but in this case.

user1555190
  • 2,803
  • 8
  • 47
  • 80

2 Answers2

5

Floating point like double is always just an (imprecise) approximation, a sum of powers of 2 - without any notion of precision = number of decimals. 55.88 and 55.879999998 could be the exactly same value (same bytes).

BigDecimal solves that. But you do not want a constructor with a double as argument, because then the precision is lost too. Use:

BigDecimal bnv = new BigDecimal("55.88");
BigDecimal bsv = new BigDecimal("2.33");

Above both have a precision of 2, a multiplication will give a precision of 4.

With BigDecimal one sometimes must provide the resulting precision for rounding and such.

So BigDecimal is superior, where it not for its horrible cobolish expressions.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
2

BigDecimal is an exact way of representing numbers and is not impacted by rounding in the manner in which double does. The issue of losing precision is when assigning to double, not when converting from double to BigDecimal.

For more details, you can see this post: Double vs. BigDecimal?

Yosi Dahari
  • 6,794
  • 5
  • 24
  • 44