简体   繁体   English

C#Math.Round问题与x.95

[英]C# Math.Round issue with x.95

Just came across one strange issue: 刚遇到一个奇怪的问题:

Math.Round(113.065, 2, MidpointRounding.ToEven) => 113.06
Math.Round(113.075, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.085, 2, MidpointRounding.ToEven) => 113.08

But... 但...

Math.Round(113.095, 2, MidpointRounding.ToEven) => 113.1

Why is this happening? 为什么会这样? I'd like my result to be 113.09! 我希望我的结果是113.09! Is that possible? 那可能吗?

Thx 谢谢

Math.Round(113.095, 2, MidpointRounding.ToEven) => 113.1

That is even . 那是偶数 Read it with two decimal places: 用两位小数读取它:

113.10 113.10

10 would be the even part. 10将是偶数部分。 The trimmed right zero is just making it look odd ("odd" in the sense of "not even", not to be confused as "odd" meaning "weird") , but that would be why it is showing that way. 修剪后的右零只是使它看起来很奇怪(“不均匀”意义上的“奇怪”,不要混淆为“奇怪”意思是“怪异”) ,但这就是为什么它表现出来的原因。

Also, your examples in your question are inaccurate. 此外,您的问题中的示例也不准确。 Here is the output from those, which would further fortify why you're getting x.1 as your output: 以下是这些的输出,这将进一步强化为什么你将x.1作为输出:

Math.Round(113.065, 2, MidpointRounding.ToEven) => 113.06
Math.Round(113.075, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.085, 2, MidpointRounding.ToEven) => 113.08

Notice that rounding 113.075 ToEven results in 113.0 8 , not 113.0 7 . 请注意,舍入113.075 ToEven导致113.0 8 ,而不是113.0 7

Full example: 完整示例:

Math.Round(113.065, 2, MidpointRounding.ToEven) => 113.06
Math.Round(113.075, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.085, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.095, 2, MidpointRounding.ToEven) => 113.1

Which can also be read as: 这也可以解读为:

Math.Round(113.065, 2, MidpointRounding.ToEven) => 113.06
Math.Round(113.075, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.085, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.095, 2, MidpointRounding.ToEven) => 113.10

If the output in your question is really what you're looking to get... (ie if that really is your desired output, and you just want to know what you have to do to get that output) 如果在你的问题的输出确实是你希望得到什么......(即,如果真的是你想要的输出,你只是想知道你必须做吃出输出什么

Math.Floor(113.065 * 100) / 100 => 113.06
Math.Floor(113.075 * 100) / 100 => 113.07
Math.Floor(113.085 * 100) / 100 => 113.08
Math.Floor(113.095 * 100) / 100 => 113.09

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM