我没有看到Math.Round的结果.
return Math.Round(99.96535789, 2, MidpointRounding.ToEven); // returning 99.97
Run Code Online (Sandbox Code Playgroud)
据我所知,MidpointRounding.ToEven,千分之五的位置应该使输出为99.96.这不是这种情况吗?
我甚至试过这个,但它也返回了99.97:
return Math.Round(99.96535789 * 100, MidpointRounding.ToEven)/100;
Run Code Online (Sandbox Code Playgroud)
我错过了什么
谢谢!
Dan*_*Tao 25
你实际上并不是在中点.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, 2, MidpointRounding.ToEven);
Run Code Online (Sandbox Code Playgroud)
嘿,这是一个方便的小函数来完成上面的一般情况:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
如果你在中点本身,它只会达到99.96,即99.965:
C:\temp>ipy IronPython 2.6 Beta 2 (2.6.0.20) on .NET 2.0.50727.4927 Type "help", "copyright", "credits" or "license" for more information. >>> import clr >>> from System import Math, MidpointRounding >>> Math.Round(99.9651, 2, MidpointRounding.ToEven) 99.97 >>> Math.Round(99.965, 2, MidpointRounding.ToEven) 99.96 >>> Math.Round(99.9649, 2, MidpointRounding.ToEven) 99.96 >>> Math.Round(99.975, 2, MidpointRounding.ToEven) 99.98 >>>
以下是阐明该主题的结果:
Math.Round(99.96535789, 2, MidpointRounding.ToEven); // returning 99.97
Math.Round(99.965, 2, MidpointRounding.ToEven); // returning 99.96
Math.Round(99.96500000, 2, MidpointRounding.ToEven); // returning 99.96
Run Code Online (Sandbox Code Playgroud)
中点正好是 5...不是 535789,也不是 499999。
归档时间: |
|
查看次数: |
9437 次 |
最近记录: |