Click to See Complete Forum and Search --> : type conversion problem


Karsten Döring
April 15th, 1999, 04:40 AM
Hi,

I have a problem with following code:

void calculateamount( long* l_amount )
{
double amount;

// amount gets calculated here
// the result is: 19.67

amount *= 100;
*l_amount = amount;

// then l_amount = 1966 and not 1967. WHY ????
// how can i prevent it?

}

Tim G
April 15th, 1999, 05:24 AM
I believe that problem is that the rounding that occurs on 196.7 is just a truncation. If this is the case simply add 0.5 to amount:

amount *= 100;
amount += 0.5;
*l_amount = amount;

This should solve the rounding problem

Karsten Döring
April 15th, 1999, 05:29 AM
when I multiply 19.67 with 100 the result is an integer: 1967 and not 196.7 as u wrote.

so this won't help me.

M Grundberg
April 15th, 1999, 05:42 AM
Well, not if the amount is actually 1966.9. Then it is rounded to 1967 if you print the double value, but when converted to an integer it is truncated to 1966.

The code:

double amount = 19.67
amount *= 100;
long l_amount = amount;

works just fine, l_amount is 1967. I can't see any other problem than the truncation...


/Michael Grundberg
M.Sc. Computer Science
Visionova IT-System, Sweden
michael@itsystem.se