I am trying to calculate the product of the following two doubles:
double x = 196.0d;
double y = 0.5144d;
double z = x * y;
The answer to this should be z = 100.8224;
but java calculates it as z = 100.82239999999999;
What is causing this?
I am trying to calculate the product of the following two doubles:
double x = 196.0d;
double y = 0.5144d;
double z = x * y;
The answer to this should be z = 100.8224;
but java calculates it as z = 100.82239999999999;
What is causing this?
The nearest double-precision floating point number to 0.5144 is 4633303296638766 / 2 ^ 53, which is actually 0.51439999999999996838084825867554. However, Java displays this as 0.5144, because it has heuristics for picking a number with fewer decimal places in the event that there is one that is close enough to a given double-precision floating point number.
When you multiply that same number by 196 though, the error is compounded, and you finish with 100.82239999999999380264625870041. This is not close enough to 100.8224 to be displayed as 100.8224, because there is another double-precision floating point number that is closer to 100.8224.
Try DecimalFormat
DecimalFormat decimalFormat = new DecimalFormat("##,###,###.####");
decimalFormat.format(z);
System.out.println(decimalFormat.format(z));
You can do it like this:
double x = 196.0d;
double y = 0.5144d;
BigDecimal bigdec = new BigDecimal(x).multiply(new BigDecimal(y));
bigdec = bigdec.setScale(4, BigDecimal.ROUND_HALF_UP);
System.out.println(bigdec.doubleValue());