微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

四舍五入到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.jb51.cc/csharp/95398.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐