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#?
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.
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.
Example: Round to the nearest hundred: 2345 would be 2300.
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;
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
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