Why java += get wrong result, and how can I prevent this? -
why java +=
wrong result, , how can prevent problem? (for example way show warning
in ide?)
i tried eclipse & intellij both not show warning.
sample code:
{ long = 20000000000000000l; double b = 90.0; += b; system.out.println(a); // 20000000000000088 ng } { long = 10000000000000000l; double b = 90.0; += b; system.out.println(a); // 10000000000000090 ok } { long = 20000000000000000l; double b = 90.0; += (long) b; system.out.println(a); // 20000000000000090 ok }
according jls, compound assignment expression
a += b;
is equivalent to
a = (long) (a + b);
since b
double
, binary numeric promotion occurs before addition happens. both operands converted double
values , addition happens floating point arithmetic.
the value 20000000000000090
cannot represented double
, therefore lose precision, getting 20000000000000088
instead. gets cast long
has enough precision represent 20000000000000088
.
your second snippet produces 10000000000000090
can represented double
.
your third snippet equivalent to
a = (long) (a + (long) b);
which uses integer arithmetic. 20000000000000090
can represented long
.
i don't know of tools warn this.
related: