本文介绍了在C#中四舍五入为偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有看到Math.Round期望的结果.

I'm not seeing the result I expect with Math.Round.

return Math.Round(99.96535789, 2, MidpointRounding.ToEven); // returning 99.97

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

As I understand MidpointRounding.ToEven, the 5 in the thousandths position should cause the output to be 99.96. Is this not the case?

我什至尝试过,但是它也返回了99.97:

I even tried this, but it returned 99.97 as well:

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

我想念什么

谢谢!

推荐答案

您实际上不在中间点. MidpointRounding.ToEven表示,如果您使用数字 99.965 ,即99.96500000 [etc.],然后然后,您将获得99.96.由于您传递给Math.Round的数字高于该中点,因此将其四舍五入.

You're not actually at the midpoint. MidpointRounding.ToEven indicates that if you had the number 99.965, i.e., 99.96500000[etc.], then you would get 99.96. Since the number you're passing to Math.Round is above this midpoint, it's rounding up.

如果您希望将数字四舍五入到99.96,请执行以下操作:

If you want your number to round down to 99.96, do this:

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

嘿,这是一个方便的小功能,适用于一般情况:

And hey, here's a handy little function to do the above for general cases:

// 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);
}

这篇关于在C#中四舍五入为偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:54