How to round a integer to the close hundred?

2019-01-06 21:45发布

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

标签: c# .net math
8条回答
成全新的幸福
2楼-- · 2019-01-06 22:39

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;
查看更多
Viruses.
3楼-- · 2019-01-06 22:41

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
查看更多
登录 后发表回答