Don't use IEEE-754 floating numbers (single
, float
, double
) for decimal calculations where all digits are equally significant (as far as business-rules are concerned). This is because IEEE-754 has rounding errors and cannot represent some trivial decimal numbers accurately. It's really meant for scientific and engineering applications where small amounts of information-loss are acceptable.
If you're dealing with fixed-precision decimal numbers (such as currency values) the best approach is to use premultiplied integers, so 100
(for 100 cents) represents 1
dollar.
If you're going to use scanf
, I recommend this:
int dollars = 0, cents = 0;
bool done = false;
while( !done ) {
done = scanf("%4d.%2d", &dollars, ¢s) != 2
}
cents += dollars * 100;
Note my use of the maximum-length specifiers (4
and 2
respectively) to prevent a buffer-overrun in scanf
.