Math.Round跟Conver.ToInt32一样,都是使用四舍六入五成双的规则,例如
Math.Round(3.2);返回3
Math.Round(3.6);返回4
Math.Round(3.5);返回4
Math.Round(2.5);返回2
要做到四舍五入,可加上参数MidpointRounding,例如
Math.Round(2.5, MidpointRounding.AwayFromZero);
如果是Math.Round(2.5, MidpointRounding.ToEven);就是默认的四舍六入五成双的规则
另外,vs2003中(.net1.1)并没有该参数,可用以下代码实现:
int result = (int)num;
double num2 = num - result;
if (num2 >= 0.5)
{
result++;
}
return result;
其他取舍函数:
Math.Floor返回小于或等于指定小数的最大整数值,例如Math.Floor(1.23);返回1
Math.Ceiling返回大于或等于指定小数的最小整数值,例如Math.Ceiling(1.23);返回2
Math.Truncate,类似于(int)强制类型转换,计算指定小数的整数部分,例如Math.Truncate(1.23);返回1
另外,Math.Round可对小数进行取舍,例如Math.Round(2.52,1);返回2.5
得到百分比代码:
public string GetPercent(decimal fenzi, decimal fenmu)
{
if (fenzi == 0 || fenmu == 0)
{
return "0.00%";
}
else
{
decimal temp = Math.Round(fenzi / fenmu * 100, 2);
return temp.ToString() + "%";
}
}