Answered by:
Converting Double To Integer

Question
-
Anyone know how to convert double to integer?
Thanks, Rob
Saturday, September 2, 2006 5:09 PM
Answers
-
look in the Convert class:
int theValueToConvert = Convert.ToInt32(doubleValue);
Saturday, September 2, 2006 5:16 PM
All replies
-
look in the Convert class:
int theValueToConvert = Convert.ToInt32(doubleValue);
Saturday, September 2, 2006 5:16 PM -
Works like a charm
Thanks
- Proposed as answer by ScoolP Tuesday, March 17, 2015 10:07 AM
Sunday, September 3, 2006 8:50 AM -
is it Ok?
int intnum=(int)doublevalue;
Monday, September 4, 2006 6:04 AM -
well thats just a direct cast...not the same as Converting it into a real/true number/integer. Its best to use the Convert classMonday, September 4, 2006 12:45 PM
-
I was a little confused about what you meant by "real/true," since the direct cast also converts it to a real integer. From MSDN, it seems that Convert.ToInt32 rounds to the nearest even number when it converts, as opposed to the truncating behavior of casting to int. Personally, I have used the direct cast much more often, in the few situations where conversion is required.Monday, September 4, 2006 4:27 PM
-
Well, ok, this thread is now about 5 years old, but, just in case someone else finds this using a Google or Bing search, here is what I found...
The direct cast should throw an exception, because, you are essentially saying object on the left is "same as" object on the right. A double with a decimal should scrunch just like trying to shove a square peg in a round hole.
The System.Convert.ToInt32(double value) failed for me because, well, it's still trying to shove a square peg in a round hole.
To be absolutely sure, do this...
double myDouble = 1234.5678;
int myInt = System.Convert.ToInt32(Math.Round(myDouble, 0));
EricThursday, November 10, 2011 9:39 PM -
No, casting will throw an exception only inside a checked block if there is an overflow, never because there is a decimal part. Convert.ToInt32 will also throw an exception only on overflow.
Your code using Math.Round throws an exception on overflow too. The only thing it adds is an unnecessary call to Math.Round.
Monday, November 14, 2011 8:03 AM -
Monday, November 14, 2011 12:31 PM