轮数到下一个最高的地方

Bri*_*ker 1 c# math rounding

我试图创建一个函数,它将返回下一个最高(缺少一个更好的术语)"圆"数,基于最大位数(最左边的数字).

例如:

 17     >  20  
 328    >  400  
 18564  >  20000

 //Already round numbers will stay the same:  
 500     >  500
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

int customRound(int i)
{
    string s = i.ToString();
    if (int.Parse(s.Substring(1)) > 0)
    {
        string greatestDigit = s.Substring(0, 1);
        string digit = (int.Parse(greatestDigit) + 1).ToString();
        return int.Parse(digit + string.Empty.PadRight(s.Length - 1, '0'));
    }
    return i;
}
Run Code Online (Sandbox Code Playgroud)

但这只是感觉非常hacky,我确信这是一个更优雅和数学方式来做到这一点.

Kla*_*ter 6

您可以使用Math.Log10来确定数字的数量级(前一个数字是10的幂),然后向上舍入到下一个数字:

int customRound(int i)
{
    var digits = (int)Math.Floor(Math.Log10(i));
    var unit = (int)Math.Pow(10, digits);
    return (int)(Math.Ceiling((double)i / unit) * unit);
}
Run Code Online (Sandbox Code Playgroud)