How do I convert a decimal to an int in C# ?

How do I convert a decimal to an int in C# ?

Asked on December 13, 2018 in C#.
Add Comment


  • 2 Answer(s)

    Note that they all return Decimal as well – since Decimal has a larger range of values than an Int32, so you’ll still need to cast (and check for overflow/underflow).

     checked {
       int i = (int)Math.Floor(d);
     }
    Answered on January 15, 2019.
    Add Comment
    7

    A neat trick for fast rounding is to add .5 before you cast your decimal to an int.

    decimal d = 10.1m;
    d += .5m;
    int i = (int)d;

    Still leavesĀ i=10, but

    decimal d = 10.5m;
    d += .5m;
    int i = (int)d;

    Would round up so thatĀ i=11.

    Answered on January 15, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.