简体   繁体   中英

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. 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. 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. If a number ends up between two integers, like 1.5, it will round to 2. Otherwise, the rounding will happen normally.

Here is the doc.

If you would like to always round up, use Math.Ceiling(my_double); .

You mention in a comment that you want to 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 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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