Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Round to the nearest whole number in C#

Tags:

c#

rounding

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?

like image 725
SOF User Avatar asked Jan 13 '12 01:01

SOF User


1 Answers

See the official documentation for more. For example:

Basically you give the Math.Round method three parameters.

  1. The value you want to round.
  2. The number of decimals you want to keep after the value.
  3. 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).

like image 165
Only Bolivian Here Avatar answered Sep 24 '22 10:09

Only Bolivian Here