Quantcast
Channel: How to round to nearest even integer? - Stack Overflow
Viewing all articles
Browse latest Browse all 6

Answer by Mark for How to round to nearest even integer?

$
0
0

The reason you are getting the result 1123 even when using

Math.Round(1122.5196d, 0, MidpointRounding.ToEven);

is because that's exactly what you have asked the compiler to do. When rounding to even with decimals, be sure to remember that 1123.0 is even.

ie. 1122.51 rounded to even becomes 1123.0 (note that as it is a decimal, it will always keep its decimal place and therefore the .0 here makes this an even number).

Instead, I would write a function to do this, something like:

   private int round_up_to_even(double number_to_round)    {        int converted_to_int = Convert.ToInt32(number_to_round);        if (converted_to_int %2 == 0) { return converted_to_int; }        double difference = (converted_to_int + 1) - number_to_round;        if (difference <= 0.5) { return converted_to_int + 1; }        return converted_to_int - 1;    }

Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>