Ekaansh Goel
Ekaansh Goel

Reputation: 1

Value changes when using double to store the value in c++ but remains same in java

I have similar code in c++ and java. There is a call by value to a double variable. I pass on a value of 1680.175 to both the codes. I can see during debugging that the value when passed changes to 1680.1749999999902 in c++ while it remains the same in java. I have to round a value after two places of decimal and therefore the codes give different result.

Upvotes: 0

Views: 96

Answers (2)

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

A double precision value has mantissa and exponent. Internally 1680.175 may be stored as 1680.1749999999902 or say 1680.1750001002 etc, i.e. close to your actual value. If precision is important then provide extra significant digits after decimal point as well.

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200196

The value didn't change at all, you just printed it such that the extra decimals showed. The value 1680.175 does not have an exact representation in the double floating-point notation and the closest value is 1680.1749999999902. The same thing goes on in Java.

Upvotes: 3

Related Questions