none
Convert Decimal to Integer RRS feed

  • Question

  • We want to convert our checkout dollars to integer.  We could have a multitude of different values such as:

    12.95
    5.00
    etc.

    so I want to convert any of these to integers rounded up.  So I want in the case of above 13 and 5.  I know there's a ToInt32() but I guess I'd have to round my decimal first then use ToInt32()?

    Convert.ToInt32(Decimal.Round(total)));

    is this the only way to do it?
    C# Web Developer
    Monday, November 2, 2009 1:52 PM

Answers

All replies

  • You can cast.  Probably the easiest way to accomplish this, if you always want to round up would be:

    int value = (int)Math.Ceiling(total));


    Coding Light - Illuminated Ideas and Algorithms in Software
    Coding Light WikiLinkedInForumsBrowser
    • Marked as answer by NoEgo Monday, November 2, 2009 9:38 PM
    Monday, November 2, 2009 2:00 PM
    Moderator
  • If you want your number to always round up so that for example 5.25 would round up to 6 you will want to use Math.Ceiling and then convert the result to an integer. Here is how the code would look:

    int number = Convert.ToInt32(Math.Ceiling(total));
    Windows Live Developer MVP - http://rbrundritt.spaces.live.com
    Monday, November 2, 2009 2:03 PM

  • i hope it could be helpfull for you 


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


    double[] values = {7.03, 7.64, 0.12, -0.12, -7.1, -7.6};
    Console.WriteLine("  Value          Ceiling          Floor\n");
    foreach (double value in values)
       Console.WriteLine("{0,7} {1,16} {2,14}", 
                         value, Math.Ceiling(value), Math.Floor(value));
    // The example displays the following output to the console:
    //         Value          Ceiling          Floor
    //       
    //          7.03                8              7
    //          7.64                8              7
    //          0.12                1              0
    //         -0.12                0             -1
    //          -7.1               -7             -8
    //          -7.6               -7             -8
    
    Monday, November 2, 2009 2:40 PM