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

Answer by Dmitry Bychenko for How to round to nearest even integer?

$
0
0

Try this (let's use Math.Round with MidpointRounding.AwayFromZero in order to obtain "next even value" but scaled - 2 factor):

double source = 1123.0;// 1124.0double result = Math.Round(source / 2, MidpointRounding.AwayFromZero) * 2;

Demo:

double[] tests = new double[] {     1.0,  1123.1,  1123.0,  1122.9,  1122.1,  1122.0,  1121.5,  1121.0,};string report = string.Join(Environment.NewLine, tests  .Select(item => $"{item,6:F1} -> {Math.Round(item / 2, MidpointRounding.AwayFromZero) * 2}"));Console.Write(report);

Outcome:

   1.0 -> 2     // In case of tie, next even value1123.1 -> 11241123.0 -> 1124  // In case of tie, next even value1122.9 -> 11221122.1 -> 11221122.0 -> 11221121.5 -> 11221121.0 -> 1122  // In case of tie, next even value

Viewing all articles
Browse latest Browse all 6

Trending Articles



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