如何在 .NET 中自定义 Math.Round 的行为?
我必须使用遵循以下行为的舍入方法:
7.00 ->圆-> 7
7.50->圆-> 7
7.51 -> 7.51圆-> 8
我尝试使用Math.Round,但它的工作方式有点不同。
Dim val As Decimal = 7.5
Dim a As Decimal = Math.Round(val, 0) ' -> 8
Dim b As Decimal = Math.Round(val, 0, MidpointRounding.AwayFromZero) ' -> 8
Dim c As Decimal = Math.Round(val, 0, MidpointRounding.ToEven) ' -> 8
如何实现我的舍入逻辑?
I have to use a round method that follows this behavior:
7.00 -> round -> 7
7.50 -> round -> 7
7.51 -> round -> 8
I tried to use Math.Round, but it works a little bit different.
Dim val As Decimal = 7.5
Dim a As Decimal = Math.Round(val, 0) ' -> 8
Dim b As Decimal = Math.Round(val, 0, MidpointRounding.AwayFromZero) ' -> 8
Dim c As Decimal = Math.Round(val, 0, MidpointRounding.ToEven) ' -> 8
How can I implement my rounding logic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以从总数中减去
0.01
,然后调用Math.round(..)
。如果数字为负数,您将必须执行以下操作才能获得相同的结果:
工作示例此处。
但请注意,正如其他几个人指出的那样,这种行为可能不是您想要的。
如果您阅读了此答案的评论,@alex zhevzhik 还指出,如果输入的小数位数超过 2 位,则此解决方案将失败。
You could subtract
0.01
from the total and then callMath.round(..)
.If the number is negative you will have to do the following to get the same result:
Working example here.
Note however that this behaviour is probably not what you want as noted by several others.
If you read the comments of this answer, @alex zhevzhik also noted that this solution will fail if the input would have more than 2 decimals.
Midpoint 无法提供适当的功能。看一下表中备注中的第一行和第三行。如果将 val 更改为 6.5,您将获得预期的行为,但如果更改为 7.5,则不会。
您应该编写自己的此类舍入实现。
Javed Akram 的实现很好,但它在处理负数时完全错误。
由于您没有提供负数舍入的详细信息,我认为标准舍入适合。此外,您应该考虑“特殊”双精度值:
Midpoint couldn't provide appropriate functionality. Take a look at first and third rows in the table in remarks. If you change your val to 6.5, you will get expected behaviour, but not with 7.5.
You should write your own implementation of such rounding.
Javed Akram's implementation is good, but it works completely wrong with negative numbers.
As you didn't provide details of rounding of negative numbers, I suppose standart rounding suits. In addition you should take into account "special" double values:
好吧,我不知道是否有 Math.Round 方法可以满足您的要求,但我认为您需要编写自己的方法。因为通常情况下,7.5 会四舍五入为 8,除非我忘记了高中所学的一切。
Well I don't know if there is a Math.Round method that does what you want, but I think you will need to write your own. Because normally, 7.5 would be rounded to 8, unless I forgot everything learned in highschool.