Casting double to int

  • Thread starter Thread starter Barry
  • Start date Start date
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.
 
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.
 
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?
 
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.
 
Back
Top