Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a integer to the close hundred?

Tags:

c#

.net

math

I don't know it my nomenclature is correct! Anyway, these are the integer I have, for example :

76 121 9660 

And I'd like to round them to the close hundred, such as they must become :

100 100 9700 

How can I do it faster in C#? I think about an algorithm, but maybe there are some utilities on C#?

like image 222
markzzz Avatar asked Oct 31 '12 08:10

markzzz


People also ask

How do you round a number to the nearest 100?

To round a number to the nearest 100, look at the tens digit. If the tens digit is 5 or more, round up. If the tens digit is 4 or less, round down. The tens digit in 3281 is 8.

How do you round a number to the nearest integer?

To round a number to the nearest whole number, you have to look at the first digit after the decimal point. If this digit is less than 5 (1, 2, 3, 4) we don't have to do anything, but if the digit is 5 or greater (5, 6, 7, 8, 9) we must round up.

What is 2345 rounded to the nearest hundreds?

Example: Round to the nearest hundred: 2345 would be 2300.


2 Answers

Try the Math.Round method. Here's how:

Math.Round(76d / 100d, 0) * 100; Math.Round(121d / 100d, 0) * 100; Math.Round(9660d / 100d, 0) * 100; 
like image 117
krizzzn Avatar answered Sep 21 '22 04:09

krizzzn


I wrote a simple extension method to generalize this kind of rounding a while ago:

public static class MathExtensions {     public static int Round(this int i, int nearest)     {         if (nearest <= 0 || nearest % 10 != 0)             throw new ArgumentOutOfRangeException("nearest", "Must round to a positive multiple of 10");          return (i + 5 * nearest / 10) / nearest * nearest;     } } 

It leverages integer division to find the closest rounding.

Example use:

int example = 152; Console.WriteLine(example.Round(100)); // round to the nearest 100 Console.WriteLine(example.Round(10)); // round to the nearest 10 

And in your example:

Console.WriteLine(76.Round(100)); // 100 Console.WriteLine(121.Round(100)); // 100 Console.WriteLine(9660.Round(100)); // 9700 
like image 33
Jason Larke Avatar answered Sep 21 '22 04:09

Jason Larke