The given values are
double double1 = 1.0814449990040142E7; double double2 = 7.0164302885665664E17;
result is double1 + double2 = 7.016430288674711E17 in Java
Manually calculated value is 701643028867471089
Can anyone resolve my issue.
The given values are
double double1 = 1.0814449990040142E7; double double2 = 7.0164302885665664E17;
result is double1 + double2 = 7.016430288674711E17 in Java
Manually calculated value is 701643028867471089
Can anyone resolve my issue.
Double values are not accurate in Java, you should use the BigDecimal class, which has a lot better precision.
For more information refer to the documentation: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
just format it how you want
double double1 = 1.0814449990040142E7;
double double2 = 7.0164302885665664E17;
System.out.printf("%.2f", double1 + double2);
output 701643028867471100.00
or
System.out.printf("%.0f", double1 + double2);
Unfortunately, this is a case of There Ain't No Such Thing As A Free Lunch.
Double gets its performance by using a compact format. Every double occupies exactly 64 bits. That allows very efficient storage and transfers between processor and memory, the use of registers to hold double values, and hardware implementation of arithmetic. A BigDecimal is a data structure whose size depends on the value being represented, but can be much bigger than 64 bits.
The price you pay for double's efficiency is that it can exactly represent only a subset of the numbers that BigDecimal can represent exactly. The closest doubles to your literals are 10814449.9900401420891284942626953125 and 701643028856656640. Their exact sum is 701643028867471089.9900401420891284942626953125. It is not itself the exact value of any double. It is bracketed by the doubles 701643028867470976 and 701643028867471104, the closer of which is the result you got.
For many purposes, doubles are close enough. For example, if your variable represents a measured physical quantity, the measurement error will dwarf the rounding error on converting to double. The numbers that can be expressed as terminating decimal fractions are no more important than other rationals and irrationals. In those cases, use double and round outputs to the number of digits justified by the input precision and accumulated rounding error.
Other cases, such as some financial calculations, require exact arithmetic on decimal fractions. Less often, decimal fractions have no special significance, but you need more precision than double can give you. In both those cases, BigDecimal is the right data type despite the performance cost.