这是我做的一个方法。它应该适合您的需求。我添加了一个额外的参数,要求在它同样接近时向上或向下舍入。(另外,如果您注意到当它们为负数时数字看起来像错误,例如 199 四舍五入到最接近的 2 舍入因子,如有必要,向上是 200。将 199 更改为 -199,结果变为 -198,这不是一个错误,它只是简单地四舍五入。)
public static double RoundToFactor(double Number, int Factor, bool RoundDirection = true)
{/*round direction: in the event that the distance is
* equal from both next factors round up (true) down (false)*/
double multiplyBy;
if ((Number % Factor).Equals(0f))
{
return Number;
}
else
{
multiplyBy = Math.Round(Number / Factor);
int Low = (int)multiplyBy - 1;
int Mid = (int)multiplyBy;
int High = (int)multiplyBy + 1;
List<double> li = new List<double>() { Low, Mid, High };
double minDelta = double.MaxValue;
double Closest = 0d;
foreach (double dbl in li)
{
double db = dbl * Factor;
double Delta = (db < Number) ? (Number - db) : (db - Number);
if (RoundDirection ? Delta <= minDelta : Delta < minDelta)
{
minDelta = Delta;
Closest = db;
}
}
return Closest;
}
throw new Exception("Math has broken!!!");
}