C#中的四舍五入
在C#中有一固定函数是处理数字舍入问题的。不过其作用是五舍六入,并且是要求double类型,如下
返回最接近指定值的整数。
[C#] public static double Round(double);//直接舍到整数
[C#] public static decimal Round(decimal, int);//int精度
[C#] public static double Round(double, int);
using System.Math;
Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4.
Math.Round(3.46, 1); //Returns 3.5.
我们可以利用这个函数来达到我们的四舍五入效果,只要……
using System.Math;
Math.Round(3.44+0.01, 1); //Returns 3.4.
Math.Round(3.45+0.01, 1); //Returns 3.5.
Math.Round(3.46+0.01, 1); //Returns 3.6.
另外还有个更简单的办法,比如只要直接舍到整数,那么这样做即可
(int)(0.5+0.5)就是1,所以,对于从十分位四舍五入到个位只要在强行转换到int之前先加0.5,其他的位类似!
浙公网安备 33010602011771号