-1

When using BigDecimal instead of double why does line 8 print 0.01 when line 4 prints 0.009999999999999998?

double a = 0.02;
double b = 0.03;
double c = b - a;
System.out.println(c); // line #4 prints 0.009999999999999998
BigDecimal _a = new BigDecimal("0.02");
BigDecimal _b = new BigDecimal("0.03");
BigDecimal _c = _b.subtract(_a);
System.out.println(_c); // line #8 prints 0.01
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
neha
  • 45
  • 5

1 Answers1

0

This happened to me sometime back, when I was working for a financial firm and a difference of 1 cent in calculation made me work for the whole weekend.

It all depends on how floating point numbers (which have two parts mantissa and exponent) are stored in hardware and always have a precision property attached to it.

doubles suffer from the same precision property(specifying how precisely it is represented).

BigDecimal is an exact representation of the floating point numbers and does not have precision. So, for any financial calculations, BigDecimal is the way to go where a difference of .0001 matters. Having said that, it is slower as compared to using double.

You should give a read to BigDecimal javadoc, it will be a good read and enlighten you.

humblefoolish
  • 409
  • 3
  • 15