How to round a integer to the close hundred?

2019-01-06 22:05发布

问题:

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#?

回答1:

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;


回答2:

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


回答3:

Try this expression:

(n + 50) / 100 * 100


回答4:

Just some addition to @krizzzn's accepted answer...

Do note that the following will return 0:

Math.Round(50d / 100d, 0) * 100;

Consider using the following and make it return 100 instead:

Math.Round(50d / 100d, 0, MidpointRounding.AwayFromZero) * 100;

Depending on what you're doing, using decimals might be a better choice (note the m):

Math.Round(50m / 100m, 0, MidpointRounding.AwayFromZero) * 100m;


回答5:

I know this is an old thread. I wrote a new method. Hope this will be useful for some one.

    public static double Round(this float value, int precision)
    {
        if (precision < -4 && precision > 15)
            throw new ArgumentOutOfRangeException("precision", "Must be and integer between -4 and 15");

        if (precision >= 0) return Math.Round(value, precision);
        else
        {
            precision = (int)Math.Pow(10, Math.Abs(precision));
            value = value + (5 * precision / 10);
            return Math.Round(value - (value % precision), 0);
        }
    }

Example:

float value = F6666.677777;
Console.Write(value.Round(2)) // = 6666.68
Console.Write(value.Round(0)) // = 6667
Console.Write(value.Round(-2)) // = 6700 


回答6:

Hi i write this extension this gets the next hundred for each number you pass

/// <summary>
    /// this extension gets the next hunfìdred for any number you whant
    /// </summary>
    /// <param name="i">numeber to rounded</param>
    /// <returns>the next hundred number</returns>
    /// <remarks>
    /// eg.:
    /// i =   21 gets 100
    /// i =  121 gets 200
    /// i =  200 gets 300
    /// i = 1211 gets 1300
    /// i = -108 gets -200
    /// </remarks>
    public static int RoundToNextHundred(this int i)
    {
        return i += (100 * Math.Sign(i) - i % 100);
        //use this line below if you want RoundHundred not NEXT
        //return i % 100 == byte.MinValue? i : i += (100 * Math.Sign(i) - i % 100);
    }

    //and for answer at title point use this algoritm
    var closeHundred = Math.Round(number / 100D)*100;

    //and here the extension method if you prefer

    /// <summary>
    /// this extension gets the close hundred for any number you whant
    /// </summary>
    /// <param name="number">number to be rounded</param>
    /// <returns>the close hundred number</returns>
    /// <remarks>
    /// eg.:
    /// number =   21 gets    0
    /// number =  149 gets  100
    /// number =  151 gets  200
    /// number = -149 gets -100
    /// number = -151 gets -200
    /// </remarks>
    public static int RoundCloseHundred(this int number)
    {
        return (int)Math.Round(number / 100D) * 100;
    }


回答7:

int num = 9660;
int remainder = num % 100;
Console.WriteLine(remainder < 50 ? num - remainder : num + (100 -remainder));

Note: I haven't tested this thoroughly.



回答8:

If you only want to round integer numbers up (as the OP actually did), then you can resort to this solution:

public static class MathExtensions
{
    public static int RoundUpTo(this int number, int nearest)
    {
        if (nearest < 10 || nearest % 10 != 0)
            throw new ArgumentOutOfRangeException(nameof(nearest), $"{nameof(nearest)} must be a positive multiple of 10, but you specified {nearest}.");

        int modulo = number % nearest;
        return modulo == 0 ? number : modulo > 0 ? number + (nearest - modulo) : number - modulo;
    }
}

If you want to perform floating-point (or decimal) rounding, then resort to the answers of @krizzzn and @Jim Aho.



标签: c# .net math