0

I've been trying to sum up decimal values using double in java and it doesn't work well, got a wrong answer.

I've already tried with Double, Float, BigDecimal.

{
    double a = 2595.00;
    double b = -1760.76;
    double c = -834.00;
    double d = -.24;

    System.out.print(a+b+c+d);
}

The expected result should be "0" But Got 9.1038288019262836314737796783447265625E-15

Sudhakar
  • 11
  • 4
  • Related: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – T.J. Crowder Aug 10 '19 at 13:48
  • 1
    *"I've already tried with Double, Float, BigDecimal"* It works with BigDecimal: http://ideone.com/oJU0Nm Perhaps you used the `BigDecimal(double)` constructor? If so, it's really worth reading [the JavaDoc](https://docs.oracle.com/javase/10/docs/api/java/math/BigDecimal.html#%3Cinit%3E(double)). – T.J. Crowder Aug 10 '19 at 13:48
  • @T.J.Crowder My guess is OP must've used the `BigDecimal(double)` constructor, which gave the wrong value upon addition. This is what I got 9.1038288019262836314737796783447265625E-15 – Fullstack Guy Aug 10 '19 at 13:51
  • 2
    @AmardeepBhowmick - Yup, see the edit to the comment. :-) – T.J. Crowder Aug 10 '19 at 13:51

2 Answers2

3

You can use BigDecimal for this purpose and make sure you input the numbers as String in the BigDecimal constructor:

 BigDecimal a = new BigDecimal("2595.00");
 BigDecimal b = new BigDecimal("-1760.76");
 BigDecimal c = new BigDecimal("-834.00");
 BigDecimal d = new BigDecimal("-.24");

 System.out.println(a.add(b).add(c).add(d));

Live Example

Output is:

0.00

From the Java docs for BigDecimal(String):

This is generally the preferred way to convert a float or double into a BigDecimal, as it doesn't suffer from the unpredictability of the BigDecimal(double) constructor.

Check this SO thread for why double results in a loss of precision.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
0

As already pointed by the previous answers about double precision, the value here is very close to zero. You can see it with System.out.format as well.

System.out.format("%.14f%n",a+b+c+d);
System.out.format("%1.1f%n",a+b+c+d); //to print 0.0
chinoy
  • 172
  • 1
  • 13