四舍五入到C#

前端之家收集整理的这篇文章主要介绍了四舍五入到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);
}
原文链接:https://www.f2er.com/csharp/95398.html

猜你在找的C#相关文章