Because of its storage format, double
s cannot store every values exactly as is is entered or displayed. The human representation of numbers is usually in decimal format, while double
s are based on the dual system.
In a double
, 120
is stored precisely because it’s an integer value. But 0.05
is not. The double is approximated to the closest number to 0.05
it can represent. 0.5
is a power of 2
(1/2
), so it can be stored precisely and you don’t get a rounding error.
To have all numbers exactly the same way you enter / display it in the decimal system, use decimal
instead.
decimal x, y;
x = 120.0M;
y = 0.05M;
decimal z = x % y; // z is 0