在 C# 中将数字四舍五入到下一个 int、百和千

Round numbers to next int, hundred and thousand in c#

我正在尝试根据某些条件对 c# 不同的数字进行舍入:

如果数字介于 0 和 100 之间,则将其四舍五入为最接近的整数。例如:8.4 = 8, 8.6 = 9 如果数字介于 101 和 10000 之间,则将其四舍五入到最接近的百位。例如:1545 = 1500、1551 = 1600

如果数字大于 10000,则四舍五入到接近千。例如:15499 = 15000、15600 = 16000。

但我试过使用 math.round 但它似乎不起作用。你能给我一个提示吗?

谢谢

此代码将完成这项工作。

double number = 1551;
if (number >= 0 && number <= 100)
{
    number = Math.Round(number);
}
else if (number > 100 && number <= 10000)
{
    number = Math.Round(number / 100) * 100;
}
else if (number > 10000)
{
    number = Math.Round(number / 1000) * 1000;
}

Console.WriteLine(number);

无论如何,我建议您不要对这些值进行硬编码,而是考虑另一种更容易抽象的逻辑。