How might I convert a double to the nearest integer value?

后端 未结 8 1933
傲寒
傲寒 2020-12-08 08:45

How do you convert a double into the nearest int?

8条回答
  •  春和景丽
    2020-12-08 09:18

    Methods in other answers throw OverflowException if the float value is outside the Int range. https://docs.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=netframework-4.8#System_Convert_ToInt32_System_Single_

    int result = 0;
    try {
        result = Convert.ToInt32(value);
    }
    catch (OverflowException) {
        if (value > 0) result = int.MaxValue;
        else result = int.Minvalue;
    }
    

提交回复
热议问题