none
Converting Double To Integer RRS feed

Answers

  • look in the Convert class:

     

    int theValueToConvert = Convert.ToInt32(doubleValue);

    Saturday, September 2, 2006 5:16 PM
    Moderator

All replies

  • look in the Convert class:

     

    int theValueToConvert = Convert.ToInt32(doubleValue);

    Saturday, September 2, 2006 5:16 PM
    Moderator
  • 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 class
    Monday, September 4, 2006 12:45 PM
    Moderator
  • 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));

     


    Eric
    Thursday, 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
  • Hi,

    Please try this link

    http://msdn.microsoft.com/en-us/library/ffdk7eyz.aspx


    Software Developer
    Monday, November 14, 2011 12:31 PM