## behaviour of static_cast

### behaviour of static_cast

Hi
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

Hammed:

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

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.

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.

HTH,

David Wilkinson

### behaviour of static_cast

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
Programmer
In|Framez

### behaviour of static_cast

This will help:

"What Every Computer Scientist Should Know About
Floating-Point Arithmetic"
http://www.yqcomputer.com/