In a comment below the question:
I would expect to receive the value 1.16 and I get a compilation error on this
You would expect 1.16 because you think you have the value 1.42. You don't. You have the double nearest to 1.42
, and while it is close enough to 142/100 (it is exactly 1.4199999999999999289457264239899814128875732421875), subtracting it many times from a large number is going to make a noticeable difference in the end.
In short, there is no way to do what you want (a % b
). There is an operation between double
, fmod(a, b)
, which does what you say, but you can only use it if you understand that it applies to double
values a
and b
, which are not represented in decimal internally.
Additional notes:
fmod
is exact: the result of the mathematical operation it stands for is always representable as a double
, and fmod
computes exactly this mathematical result. On the other hand, other floating-point operations are not exact, including conversion from decimal in the case of the decimal representation “1.42”.
fmod(9999999.0, 1.42)
is computed exactly as 1.16000000050038210019920370541512966156005859375
. In this expression, 9999999.0
represents exactly the value 999999999. The error only comes from the difference between 1.42
and 142/100.