How can I round values to nearest integer?
For example:
1.1 => 1 1.5 => 2 1.9 => 2
"Math.Ceiling()" is not helping me. Any ideas?
See the official documentation for more. For example:
Basically you give the Math.Round
method three parameters.
Sample code:
var roundedA = Math.Round(1.1, 0); // Output: 1 var roundedB = Math.Round(1.5, 0, MidpointRounding.AwayFromZero); // Output: 2 var roundedC = Math.Round(1.9, 0); // Output: 2 var roundedD = Math.Round(2.5, 0); // Output: 2 var roundedE = Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // Output: 3 var roundedF = Math.Round(3.49, 0, MidpointRounding.AwayFromZero); // Output: 3
Live Demo
You need MidpointRounding.AwayFromZero
if you want a .5 value to be rounded up. Unfortunately this isn't the default behavior for Math.Round()
. If using MidpointRounding.ToEven
(the default) the value is rounded to the nearest even number (1.5
is rounded to 2
, but 2.5
is also rounded to 2
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With