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

后端 未结 12 2444
再見小時候
再見小時候 2020-12-02 13:47

How do I convert a decimal to an int?

12条回答
  •  猫巷女王i
    2020-12-02 14:24

    int i = (int)d;
    

    will give you the number rounded down.

    If you want to round to the nearest even number (i.e. >.5 will round up) you can use

    int i = (int)Math.Round(d, MidpointRounding.ToEven);
    

    In general you can cast between all the numerical types in C#. If there is no information that will be lost during the cast you can do it implicitly:

    int i = 10;
    decimal d = i;
    

    though you can still do it explicitly if you wish:

    int i = 10;
    decimal d = (decimal)i;
    

    However, if you are going to be losing information through the cast you must do it explicitly (to show you are aware you may be losing information):

    decimal d = 10.5M;
    int i = (int)d;
    

    Here you are losing the ".5". This may be fine, but you must be explicit about it and make an explicit cast to show you know you may be losing the information.

提交回复
热议问题