Built in .Net Algorithm to Round Value to the Nearest 10 Interval

Built in .Net algorithm to round value to the nearest 10 interval

There is no built-in function in the class library that will do this. The closest is System.Math.Round() which is only for rounding numbers of types Decimal and Double to the nearest integer value. However, you can wrap your statement up in a extension method, if you are working with .NET 3.5, which will allow you to use the function much more cleanly.

public static class ExtensionMethods
{
public static int RoundOff (this int i)
{
return ((int)Math.Round(i / 10.0)) * 10;
}
}

int roundedNumber = 236.RoundOff(); // returns 240
int roundedNumber2 = 11.RoundOff(); // returns 10

If you are programming against an older version of the .NET framework, just remove the "this" from the RoundOff function, and call the function like so:

int roundedNumber = ExtensionMethods.RoundOff(236); // returns 240
int roundedNumber2 = ExtensionMethods.RoundOff(11); // returns 10

Rounding integers to nearest multiple of 10

I would just create a couple methods;

int RoundUp(int toRound)
{
if (toRound % 10 == 0) return toRound;
return (10 - toRound % 10) + toRound;
}

int RoundDown(int toRound)
{
return toRound - toRound % 10;
}

Modulus gives us the remainder, in the case of rounding up 10 - r takes you to the nearest tenth, to round down you just subtract r. Pretty straight forward.

Round a number to the next HIGHEST 10

if(rangeMax % 10 !=0)
rangeMax = (rangeMax - rangeMax % 10) + 10;

You could also use Math.Round() with MidpointRounding.AwayFromZero using a decimal number (otherwise integer division will truncate fractions):

decimal number = 55M;
decimal nextHighest = Math.Round(number/ 10, MidpointRounding.AwayFromZero) * 10;

How do I round a number (any number) down by 100s?

This will do it:

private static int RoundDown(int input)
{
return input / 100 * 100;
}

The reason this works is as follows:

Dividing an integer value by 100 will give the integer portion of the result. This means, if we take the integer 199 and divide by 100, the mathematical result is 1.99 but because we're working with integers, only the 1 is retained. Multiplying this value again by 100 will give you 100 which is the desired result.

Math.Round() call in .NET using negative precision

Move the comma to the precision you want to give back and then round.

        double n = 43.34566;
double roundingValue = -1;
double precision = Math.Pow(10, roundingValue);
n *= precision;
double result = Math.Round(n, 0) / precision;


Related Topics



Leave a reply



Submit