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

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

$
0
0

One liner:

double RoundToNearestEven(double value) =>    Math.Truncate(value) + Math.Truncate(value) % 2;

Fiddle

Explanation: if we have an even number with some digits after floating point, we need to just get rid of those digits. If we have an odd number, we need to do the same and then move to the next integer that is guaranteed to be even.

P.S. Thanks to @DmitryBychenko for pointing out that casting double to long is not the brightest idea.


Viewing all articles
Browse latest Browse all 6

Trending Articles



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