简体   繁体   English

为什么MidpointRounding.AwayFromZero和MidpointRounding.ToEven做同样的事情?

[英]Why does MidpointRounding.AwayFromZero and MidpointRounding.ToEven do the same thing?

I've encountered a rather annoying problem. 我遇到了一个很烦人的问题。

Lets say I have the decimal 2.5, and I would like it rounded up. 可以说我有十进制的2.5,我希望将其取整。 All my research has told me is that: 我所有的研究告诉我:

Math.Round(2.5, 0, MidpointRounding.AwayFromZero)

Will give me the desired result. 会给我想要的结果。

Yet, when trying exactly that piece of code, it returns 2, not 3 as it should. 但是,当完全尝试这段代码时,它将返回2,而不是应有的3。 It even does it in a blank console application, as I was unsure if something else might be interfering with it. 它甚至可以在空白的控制台应用程序中执行此操作,因为我不确定是否可能有其他干扰。

Am I misunderstanding something here? 我在这里误会什么吗? Basically I just want the number I give it rounded up at all times. 基本上,我只想一直给定它的数字。

You want to use AwayFromZero. 您要使用AwayFromZero。 If a number ends up between two integers, like 1.5, it will round to 2. Otherwise, the rounding will happen normally. 如果数字以两个整数(例如1.5)结尾,则将舍入为2。否则,舍入将正常进行。

Here is the doc. 是文档。

If you would like to always round up, use Math.Ceiling(my_double); 如果您希望始终四舍五入,请使用Math.Ceiling(my_double); .

You mention in a comment that you want to convert an int to half it's value, always rounded up . 您在注释中提到convert an int to half it's value, always rounded up

The most efficient way to do that, assuming that the int is positive, is simply: 假设int为正,最有效的方法是:

int result = (value+1)/2;

If you need to handle positive AND negative values, 如果您需要处理正值和负值,

int result = (value+Math.Sign(x))/2;

Figured out the solution: 找出解决方案:

Basically in my code I was retrieving the an int from an input field, it was default cast as an int, so when I halved it, it was automatically rounded down (so for example, 5 / 2 = 2, not 2.5 as I was expecting). 基本上在我的代码中,我从输入字段中检索一个int,默认情况下将其强制转换为int,因此当我将其减半时,它会自动舍入(例如5/2 = 2,而不是2.5。期待)。

The solution was to cast the input number do a decimal. 解决的办法是将输入数字强制转换为十进制。

Code snippet with correction: 带有更正的代码段:

// strong is the input value
decimal calc = (decimal)strong / 2;

// targetInput is the input field for the result
targetInput.text = (Math.Round(calc, 0, MidpointRounding.AwayFromZero)).ToString();

Sorry if I wasted anyones time. 对不起,如果我浪费任何人的时间。

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

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