Aside from the obvious expected loss of fractional values, I don't see why this should happen...
Consider the following snippet from a homework assignment used to convert numerical digits to english phrases:
int main() {
float dollars;
cout << "Please supply a dollar amount between $0.01 and $9999.99 (without the dollar sign): ";
while (true) {
cin >> dollars;
if (cin.fail() || dollars < 0.01 || dollars > 9999.99) {
cin.clear();
cin.ignore();
cout << "You provided an invalid number. Please try again: ";
} else {
// Test code:
cout << "You entered: " << dollars << endl;
cout << "Times 100 without cast: " << dollars * 100 << endl;
cout << "Times 100 with cast: " << (int)(dollars * 100) << endl;
cout << "Cents: " << ((int)(dollars * 100)) % 100 << endl;
break;
}
}
printDollarsAsString(dollars);
return 0;
}
I've noticed that when supplying the value 9999.21
, the outputs of the second and third cout
statements in the else
block differ by 1. For example, here is the output when I run this code:
Please supply a dollar amount between $0.01 and $9999.99 (without the dollar sign): 9999.21
You entered: 9999.21
Times 100 without cast: 999921
Times 100 with cast: 999920
Cents: 20
How can I fix this so that the cents value is retrieved correctly? Is there a different approach I can take?