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

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

How do you convert a double into the nearest int?

相关标签:
8条回答
  • 2020-12-08 09:32

    You can also use function:

    //Works with negative numbers now
    static int MyRound(double d) {
      if (d < 0) {
        return (int)(d - 0.5);
      }
      return (int)(d + 0.5);
    }
    

    Depending on the architecture it is several times faster.

    0 讨论(0)
  • 2020-12-08 09:35

    Use Math.round(), possibly in conjunction with MidpointRounding.AwayFromZero

    eg:

    Math.Round(1.2) ==> 1
    Math.Round(1.5) ==> 2
    Math.Round(2.5) ==> 2
    Math.Round(2.5, MidpointRounding.AwayFromZero) ==> 3
    
    0 讨论(0)
提交回复
热议问题