Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

issues when convert a double to a long

Status
Not open for further replies.

SpeedBWild

Programmer
Apr 29, 2004
117
0
0
US
I am reading in a line of data so that I can insert the text data into an array. Here is my code:
double rate;
rate = atof (&wktxt[k]); /* &wktxt[k]=2.046 */
rate *= 1000.0;
prate[cin][x] = (long) rate;

The result of prate[cin][x] is 2045

I have hundreds of values in the text file all of them convert as expected except 2.046. If I add this line of
code rate += .00000000001; (see below) then it converts correctly.

rate *= 1000.0;
rate += .00000000001;
prate[cin][x] = (long) rate;

Any ideas? Has anyone else experienced anything like this before?





 
If your intent is to store an int, then don't read it in as a float just because it's an easy way of dealing with the decimal point.

Read it in as two ints separated by a '.' and perform appropriate arithmetic to combine those two ints into a result.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Use some kind of rounding, for example:
Code:
prate[cin][x] = (long) (rate+0.5);
(to nearest value for positive numbers).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top