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
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…