第 1,7346 轮至 1,74
我使用 Math.Round(1.7346, 2, AwayFromZero) 应该给我 1,74 - 但它实际上给我 1.73。
我知道是因为这个:
“因为表示可能导致精度损失 十进制值作为浮点数或执行算术 对浮点值的运算,在某些情况下是 Round(Double, Int32, MidpointRounding) 方法可能不会出现舍入中点的情况 由模式参数指定的值。这在 以下示例中,2.135 四舍五入为 2.13,而不是 2.14。 发生这种情况是因为该方法在内部将值乘以 10 * 数字,并且在这种情况下的乘法运算会遇到 精度损失。”
但是我实际上应该使用哪种 .NET 方法来进行正确的舍入?
I use Math.Round(1.7346, 2, AwayFromZero)
which should give me 1,74 - but it actually gives me 1.73.
I know it is because of this:
"Because of the loss of precision that can result from representing
decimal values as floating-point numbers or performing arithmetic
operations on floating-point values, in some cases the Round(Double,
Int32, MidpointRounding) method may not appear to round midpoint
values as specified by the mode parameter. This is illustrated in the
following example, where 2.135 is rounded to 2.13 instead of 2.14.
This occurs because internally the method multiplies value by 10 *
digits, and the multiplication operation in this case suffers from a
loss of precision."
But which .NET Method should I actually use to do correct rounding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
1.7346 应四舍五入为 1.73,即使使用
AwayFromZero
,因为这只改变“当一个数字介于两个其他数字之间时”的舍入行为(例如,如果它是 1.735)。可以通过以下方式获得您想要的行为
(但不要认为这只是一种黑客行为)。
1.7346 should be rounded to 1.73, even with
AwayFromZero
, since that only changes the rounding behavior "when a number is halfway between two others" (e.g. if it had been 1.735).The behavior you want can be obtained with
(but don't consider this anything more than a hack).
你的假设部分是错误的。由于
AwayFromZero
的语义,1.7346 四舍五入为 1.73,即:0.5→0.0
为了避免浮点运算引起的问题,请使用十进制数字系统中精确的
decimal
数据类型。要开发“自定义”舍入到最接近的较大或最接近的较小数字,您可以使用
Math.Ceiling
或Math.Floor
分别。它们都可用于double
和decimal
类型。Your assumption is partly wrong. 1.7346 is rounded to 1.73 because of the semantics of
AwayFromZero
, i.e.:To avoid problems caused by floating-point arithmetic use the
decimal
data type which is precise in terms of the decimal numeral system.To develop a 'custom' rounding to the nearest greater or the nearest lower number you can use
Math.Ceiling
orMath.Floor
respectively. They are both available fordouble
anddecimal
types.四舍五入:) 希望有所帮助
正如所述.. 1.7345 应该向下舍入.. 因为 1.7351 将使用 Math.Round() 进行四舍五入。
所以,你必须知道你想要什么..
Rounds up :) Hope that helps
And as stated.. 1.7345 should round down.. because 1.7351 will round up with Math.Round().
So, you have to know what you want..
我认为 Math.Round() 如此工作的原因已经被其他人解决了。
获得所需结果的另一种方法是将 0.005 添加到值:
Math.Round(1.7346 + 0.005, 2, AwayFromZero)
I think the reason why
Math.Round()
works that way have been addressed by others.Another way to get your desired result is to add 0.005 to the value:
Math.Round(1.7346 + 0.005, 2, AwayFromZero)