0

Why I'm getting this weird answer?
35458.450000000004 instead of 35458.45
using java6,7 & 8.

public static void main(String[] args) {
    double[] as = new double[]{ 1000.0, 1174.0, 1000.0, 2131.0, 240.0,
      390.0, 21524.15, 6426.5, 1272.8, 100.0, 200.0};

    double v = 0;
    for(int i = 0; i < as.length; i++) {
        v += as[i];
    }

    System.out.println(v);
}

In Scala (same):

    scala> val as = List(1000.0, 1174.0, 1000.0, 2131.0, 240.0, 390.0, 21524.15, 6426.5, 1272.8, 100.0, 200.0 );
    scala> as.sum
    res3: Double = 35458.450000000004
mijzcx
  • 17
  • 2
  • 2
    `Double` is not infinitely percise, if you need percise decimal calculations consider opting for `BigDecimal` class instead of `Double` – Ceiling Gecko Jul 21 '16 at 07:15
  • 1
    Just read http://floating-point-gui.de/. – Alexey Romanov Jul 21 '16 at 07:17
  • This exact question has been asked seemingly a million times. Please at least do a search first before posting a question. – Fildor Jul 21 '16 at 07:19
  • See also: [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) and [floating-point-gui.de](http://floating-point-gui.de/). – Jesper Jul 21 '16 at 07:25

2 Answers2

1

double and float are influenced by the internal binary representation, when converted to decimal representation.

If you need to have arbitrary precision arithmetic you need to use BigDecimal:

Immutable, arbitrary-precision signed decimal numbers.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
1

Its the type you are using. Use BigDecimal

Alexius DIAKOGIANNIS
  • 2,465
  • 2
  • 21
  • 32