四舍五入到C#

我没有看到我期望与Math.Round的结果.
return Math.Round(99.96535789,2,MidpointRounding.ToEven); // returning 99.97

据了解MidpointRounding.ToEven,千分之五的位置应该使输出为99.96.不是这样吗?

我甚至尝试过这个,但是它也返回了99.97:

return Math.Round(99.96535789 * 100,MidpointRounding.ToEven)/100;

我失踪了

谢谢!

解决方法

你实际上并不在中点. MidpointRounding.ToEven表示如果你的号码是99.965,即99.96500000 [等],那么你会得到99.96.由于您传递给Math.Round的数字在该中点之上,所以它正在四舍五入.

如果您希望将您的号码缩小到99.96,请执行以下操作:

// this will round 99.965 down to 99.96
return Math.Round(Math.Truncate(99.96535789*1000)/1000,MidpointRounding.ToEven);

嘿,这里有一个很方便的小功能来做上面的一般情况:

// This is meant to be cute;
// I take no responsibility for floating-point errors.
double TruncateThenRound(double value,int digits,MidpointRounding mode) {
    double multiplier = Math.Pow(10.0,digits + 1);
    double truncated = Math.Truncate(value * multiplier) / multiplier;
    return Math.Round(truncated,digits,mode);
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...