The important thing to note about
floating-point numbers, e.g.
float
or
double
, is that they have a
limited precision, but
not in the sense that (only) a
fixed number of "fraction digits" is preserved ðŸ˜¨
Instead, the number of "fraction digits" that will be preserved depends on how "big" the number is. Simply put, for "smaller" numbers
more "fraction digits" are persevered. And for "bigger" numbers
fewer "fraction digits" are persevered. For "extremely large" numbers,
not even the
integral part is preserved accurately!
So, as others have pointed out,
floating-point numbers are a bad choice to represent things like money. Therefore, you should go with an
integer type that represents the smallest "unit" of money that you need to deal with. Either that, or consider using "arbitrary precision"
rational numbers, as provided by GMP:
https://gmplib.org/