Precision Errors

solved thank you
Last edited on
Floating point values are weird and strange. You should keep sums internally as integral value with small enough unit (say penny). Integer math -- division and modulus -- work a treat. When you absolutely have to print a decimal number, do the conversion only for the print.

You have to take decimal input though:
1
2
3
double price;
std::cin >> price;
const int internalprice = static_cast<int>( 100 * price ); // price in pennies 

Just hope it doesn't round too bad.


PS. Please use the code tags (and indentation). See http://www.cplusplus.com/articles/jEywvCM9/
Last edited on
> Just hope it doesn't round too bad.
use http://www.cplusplus.com/reference/cmath/round/ instead of just casting
Oh, yes. That thingy.
const int internalprice = static_cast<int>( 100 * price + 0.5 );
The rationale is that the cast discards fraction, and if your "3" for some reason is 2.99999, adding 0.5 gives about 3.49999, which converts to 3.


The rounding functions in cmath return double; you still have to cast, if you store as integer.
Topic archived. No new replies allowed.