我不知道我的命名是否正确!无论如何,这些是我的整数,例如:
76
121
9660
Run Code Online (Sandbox Code Playgroud)
而且我想将它们四舍五入到近百,例如他们必须成为:
100
100
9700
Run Code Online (Sandbox Code Playgroud)
如何在C#中更快地完成?我想一个算法,但也许C#上有一些实用程序?
kri*_*zzn 75
试试这个Math.Round方法.这是如何做:
Math.Round(76d / 100d, 0) * 100;
Math.Round(121d / 100d, 0) * 100;
Math.Round(9660d / 100d, 0) * 100;
Run Code Online (Sandbox Code Playgroud)
Jas*_*rke 23
我写了一个简单的扩展方法来概括这种舍入:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
它利用整数除法来找到最接近的舍入.
使用示例:
int example = 152;
Console.WriteLine(example.Round(100)); // round to the nearest 100
Console.WriteLine(example.Round(10)); // round to the nearest 10
Run Code Online (Sandbox Code Playgroud)
在你的例子中:
Console.WriteLine(76.Round(100)); // 100
Console.WriteLine(121.Round(100)); // 100
Console.WriteLine(9660.Round(100)); // 9700
Run Code Online (Sandbox Code Playgroud)
Mar*_*tos 16
试试这个表达式:
(n + 50) / 100 * 100
Run Code Online (Sandbox Code Playgroud)
只是@krizzzn接受的答案的一些补充......
请注意以下内容将返回0:
Math.Round(50d / 100d, 0) * 100;
Run Code Online (Sandbox Code Playgroud)
考虑使用以下内容并使其返回100:
Math.Round(50d / 100d, 0, MidpointRounding.AwayFromZero) * 100;
Run Code Online (Sandbox Code Playgroud)
根据您正在做的事情,使用小数可能是更好的选择(注意m):
Math.Round(50m / 100m, 0, MidpointRounding.AwayFromZero) * 100m;
Run Code Online (Sandbox Code Playgroud)
我知道这是一个老线程.我写了一个新方法.希望这对某些人有用.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
例:
float value = F6666.677777;
Console.Write(value.Round(2)) // = 6666.68
Console.Write(value.Round(0)) // = 6667
Console.Write(value.Round(-2)) // = 6700
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37429 次 |
| 最近记录: |