How to Round to the nearest whole number in C#
Solution 1:
See the official documentation for more. For example:
Basically you give the Math.Round
method three parameters.
- The value you want to round.
- The number of decimals you want to keep after the value.
- An optional parameter you can invoke to use AwayFromZero rounding. (ignored unless rounding is ambiguous, e.g. 1.5)
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
).
Solution 2:
Math.Ceiling
always rounds up (towards the ceiling)
Math.Floor
always rounds down (towards to floor)
what you are after is simply
Math.Round
which rounds as per this post
Solution 3:
You need Math.Round
, not Math.Ceiling
. Ceiling
always "rounds" up, while Round
rounds up or down depending on the value after the decimal point.