double to int - will I ever have this problem?

Example:

1
2
double d = 3.0000;
int i = d;


Could i ever equal 2? Does the computer store d like 3.000.....321 and 2.999....99732? Or only ever the first? I don't really know anything about how floating point numbers are stored.

I have a number which I know is an integer but is stored in the file in float format, i.e. 3.0000. So when I read it I'm using fscanf(file,"%lf",*double). However I want to use it for loops and other stuff - like array indexes and map keys. So can I just assign the double to an int - as shown in the code above - is this safe?

Anyway, any advice would be awesome.

Thanks.

Nick.
Last edited on
Three is three.
There should be no inaccuracies with integers below 2^52 in a double variable.
It can be "dangerous" as the value in the double could either be higher than what an int can handle, or have decimal values that will be lost when stored in an int. Depending on the use, this may or may not be an issue.
That danger does exist. A solution could be to add 0.5 to your double before converting it to an integer.
Thanks for the replies! Hamsterman that is exactly what I'll do - great thinking!

Nick.
I think hamsterman's solution is senseless.

Because:

1
2
3
4
5
Without your method                             With your method
3000.22 -> 3000                                    3000.22 -> 3001
2999.88 -> 3000                                    2999.88 -> 3000
0            -> 0                            0            -> 0
0.49       -> 0                                          0.49       -> 1

Tagged as code so it looks better.

The best thing to do is:

1
2
double d = 3.000;
int i = int(d);

if you don't do like this, you may get a warning.
Last edited on
@EssGeEich, conversions from double to int round down. That's written in the standard (4.9). So 2999.88 -> 2999
Adding 0.5 makes rounding unbiased.
Last edited on
Adding 0.5 makes rounding unbiased.
It doesn't apply to negative values though
lols, reminds me of the "whole" part and the "mantissa" from assembly class and the IEEE standard of how a double is represented in memory.... anyway if you are not worried about data loss, then truncate that shiz...:
var = static_cast <data type> (var to cast);
if you are worried about about a particular memory location, then use a pointer and memory arithmetic:
var = pointer* (base addy of var, if you know the size of the addy type then do pointer math) and dereference when needed :)
Topic archived. No new replies allowed.