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

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

How do you convert a double into the nearest int?

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 09:22

    I'm developing a scientific calculator that sports an Int button. I've found the following is a simple, reliable solution:

    double dblInteger;
    if( dblNumber < 0 )
       dblInteger = Math.Ceiling(dblNumber);
    else
       dblInteger = Math.Floor(dblNumber);
    

    Math.Round sometimes produces unexpected or undesirable results, and explicit conversion to integer (via cast or Convert.ToInt...) often produces wrong values for higher-precision numbers. The above method seems to always work.

提交回复
热议问题