behaviour of static_cast

behaviour of static_cast

Post by Hameed U. » Thu, 03 Aug 2006 20:39:58

following is the code snipped of my program which is working fine. But
there is a poing in program when it start losing data. Like in the
program below when I'll enter value 1.15 it will print 114 when I
multiply the value with 100 and assign it to long. But if i print it
without assigning to a variable like in Step 1 it prints 115. I'm Using
VS2005 Express Edition. I think there is something wrong with
static_cast or with assigning it to a variable of type long, but I
can't figure it out.

int main()
long money = 0;
double hold_money = 0.0;
long quarters = 0;
long dimes = 0;
long nickels = 0;
long cents = 0;
long one_quart = 25;
long one_dime = 10;
long one_nickel = 5;
long one_cent = 1;

cout <<"Enter money between $0 and $10: ";
cin >> hold_money;
cout << hold_money*100<<endl; // Step 1
money = static_cast<int>(hold_money * 100);

cout << money<<endl; // Step 2
return 0;

Hameed U. Khan

behaviour of static_cast

Post by David Wilk » Thu, 03 Aug 2006 21:20:30


This is normal behavior for floating point variables. When you write for

double x = 1.15;

the actual value stored in the computer might be slightly less than 1.15
or slightly more. Casting a double to a integer gives the integer part,
so if you multiply by 100 and cast, you might get either 114 or 115.
Both answers are "correct".

One way to fix this is to write

money = static_cast<long>(hold_money * 100 + 0.5);

This will "round up" to the next integer when the fractional part is >=
0.5 . Note that if "money" is a long you should cast to long, not int.


David Wilkinson


behaviour of static_cast

Post by Abdo Haji- » Thu, 03 Aug 2006 22:18:03

Nope, it's not static_cast. It's the approximation of double. When you
assign 1.15 to a double variable, that varaible will actually contain an
approximation of 1.15 (Something like 1.1499999...) That's why when you
multiply that variable by 100 it will contain 114.999999999 not 115, then
assigning it to an integer would truncate the fraction.
Now the question is why does cout output the value "correctly"? Because it
rounds double to the nearest precision (which can be set using
std::setprecision()), for example consider:
cout<< std::setprecision(20) << 1.15 << endl;
it would print 1.149999...

Hope that helps,
Abdo Haji-Ali

behaviour of static_cast

Post by Alex Blekh » Fri, 04 Aug 2006 00:36:41

This will help:

"What Every Computer Scientist Should Know About
Floating-Point Arithmetic"