C# 如何将整数四舍五入到接近百位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13153616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:46:55  来源:igfitidea点击:

How to round a integer to the close hundred?

c#.netmath

提问by markzzz

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# 中更快地做到这一点?我在考虑一种算法,但也许 C# 上有一些实用程序?

采纳答案by krizzzn

Try the Math.Roundmethod. Here's how:

试试这个Math.Round方法。就是这样:

Math.Round(76d / 100d, 0) * 100;
Math.Round(121d / 100d, 0) * 100;
Math.Round(9660d / 100d, 0) * 100;

回答by Marcelo Cantos

Try this expression:

试试这个表达式:

(n + 50) / 100 * 100

回答by Jason Larke

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

回答by shahkalpesh

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

Note: I haven't tested this thoroughly.

注意:我还没有彻底测试过。

回答by Raghu

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 

回答by Jim Aho

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

只是@krizzzn接受的答案的一些补充......

Do note that the following will return 0:

请注意,以下将返回 0:

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

Consider using the following and make it return 100 instead:

考虑使用以下内容并使其返回 100:

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

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

根据您在做什么,使用小数可能是更好的选择(注意m):

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

回答by luka

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;
    }

回答by feO2x

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

如果您只想将整数向上舍入(正如 OP 实际所做的那样),那么您可以使用以下解决方案:

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.

如果您想执行浮点(或小数)舍入,请求助于 @krizzzn 和 @Jim Aho 的答案。

回答by Chris

I had a similar project internally where the business requirements were to search within the 100's range of a given number and find duplicate DB records. So if the user was using line 856 I would search 800 - 899. If the user was using 8567 I would search 8500 - 8599. Not an exact rounding by 100's, but thought I would include my unique approach as some of these basic coding questions are embedded within a larger business project. To test this I seeded a decimal list from 1 - 99999 and spit the results out into a file.

我在内部有一个类似的项目,其中业务需求是在给定数字的 100 范围内搜索并找到重复的数据库记录。因此,如果用户使用第 856 行,我会搜索 800 - 899。如果用户使用 8567,我会搜索 8500 - 8599。不是精确的 100 舍入,但我想我会包括我的独特方法作为这些基本编码问题中的一些嵌入在一个更大的商业项目中。为了测试这一点,我从 1 - 99999 中植入了一个十进制列表,并将结果输出到一个文件中。

    /// <summary>
    /// This method accepts an inbound Line Number and returns the line range
    /// in the form of lowest to highest based on 100's
    /// Example would be 9122 returns 9100 - 9199
    /// It's used for generating some additional BOM Temp functionality.
    /// </summary>
    /// <param name="inboundNumber"></param>
    /// <returns></returns>
    public static ProjectLineRange CalculateLineRange(decimal inboundNumber)
    {
        var lineRange = new ProjectLineRange();
        var numberLength = inboundNumber.ToString(CultureInfo.InvariantCulture).Length;

        switch (numberLength)
        {
            case 0: //NULL?
                break;
            case 1: //Represents 1 - 9
                lineRange.LineBottom = 1;
                lineRange.LineTop = 99;
                break;
            case 2: //Represents 10 - 99
                lineRange.LineBottom = 1;
                lineRange.LineTop = 99;
                break;
            case 3: //Represents 100 - 999
                lineRange = CalculateHundredsRange((int)(inboundNumber / 100));
                break;
            case 4: //Represents 1000 - 9999
                lineRange = CalculateThousandsRange(
                    Convert.ToInt32(inboundNumber.ToString(CultureInfo.InvariantCulture).Substring(1, 1)),
                    Convert.ToInt32(inboundNumber.ToString(CultureInfo.InvariantCulture).Substring(0, 1)));
                break;
            case 5: //Represents 10000 - 99999
                lineRange = CalculateTenThousandsRange(
                    Convert.ToInt32(inboundNumber.ToString(CultureInfo.InvariantCulture).Substring(2, 1)),
                    Convert.ToInt32(inboundNumber.ToString(CultureInfo.InvariantCulture).Substring(1, 1)),
                    Convert.ToInt32(inboundNumber.ToString(CultureInfo.InvariantCulture).Substring(0, 1)));
                break;
        }

        return lineRange;
    }

public class ProjectLineRange
    {
       public decimal LineBottom { get; set; }
       public decimal LineTop { get; set; }
    }

    /// <summary>
    /// Helper method to return the range for the 100's place
    /// </summary>
    /// <param name="hundredsPlaceValue"></param>
    /// <returns></returns>
    public static ProjectLineRange CalculateHundredsRange(int hundredsPlaceValue)
    {
        var tempLineRange = new ProjectLineRange();
        tempLineRange.LineBottom = hundredsPlaceValue * 100;
        tempLineRange.LineTop = tempLineRange.LineBottom + 99;

        return tempLineRange;
    }

    /// <summary>
    /// Helper method to return the range for the 100's place when factoring a 1000's number
    /// </summary>
    /// <param name="hundredsPlaceValue"></param>
    /// <param name="thousandsPlaceValue"></param>
    /// <returns></returns>
    public static ProjectLineRange CalculateThousandsRange(int hundredsPlaceValue, int thousandsPlaceValue)
    {
        var tempLineRange = new ProjectLineRange();
        var tempThousands = thousandsPlaceValue * 1000;
        var hundredsRange = CalculateHundredsRange(hundredsPlaceValue);
        tempLineRange.LineBottom = tempThousands + hundredsRange.LineBottom;
        tempLineRange.LineTop = tempThousands + hundredsRange.LineTop;

        return tempLineRange;
    }

    /// <summary>
    /// Helper method to return the range for the 100's place when factoring a 10000's number
    /// </summary>
    /// <param name="hundredsPlaceValue"></param>
    /// <param name="thousandsPlaceValue"></param>
    /// <param name="tenThousandsPlaceValue"></param>
    /// <returns></returns>
    public static ProjectLineRange CalculateTenThousandsRange(int hundredsPlaceValue, int thousandsPlaceValue, int tenThousandsPlaceValue)
    {
        var tempLineRange = new ProjectLineRange();
        var tempThousands = thousandsPlaceValue * 1000;
        var tempTenThousands = tenThousandsPlaceValue * 10000;
        var hundredsRange = CalculateHundredsRange(hundredsPlaceValue);
        tempLineRange.LineBottom = tempTenThousands + tempThousands + hundredsRange.LineBottom;
        tempLineRange.LineTop = tempTenThousands + tempThousands + hundredsRange.LineTop;

        return tempLineRange;
    }