Casting double to int

B

Barry

What is the best way to round a double and store it in an int (C#)?
I'm currently using
intVar = (int)Math.Round(doubleVar);
I'm worried that the return value of e.g. Math.Round(2.1) might be
1.99999999999999999999999 (due to quirks of binary/decimal conversion),
and (int) will then truncate it to 2.
 
C

chris

You could use:

int number = (int)Math.Ceiling(doubleValue);

The smallest whole number greater than or equal to doubleValue.

int number = Convert.ToInt32(doubleValue);

rounds it to the nearest number.
 
G

Guest

I'm worried that the return value of e.g. Math.Round(2.1) might be
and (int) will then truncate it to 2.

Doesn't 2.1 round to 2 ?

How about:

int i = (int) (d+0.5)

Are you testing against a bunch of samples and seeing erroneous results? Or
are you perhaps worrying needlessly?
 
B

Bruno Jouhier [MVP]

ints are *exactly* representable as double, and longs are too when smaller
than 2^52 in absolute value.

So, Math.Round(someDecimal) will never be something like
someInt.99999999999999999999, it will be exactly someInt.000000000000000 and
the cast will always give the correct result.

But this is a special case, and most decimal numbers are *not* exactly
representable as doubles. So, you are right to be careful about this.

Bruno.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top