This question already has answers here:
Returning the nearest multiple value of a number

(6个答案)


1年前关闭。




我试图弄清楚如何对价格进行取整-双向。例如:
Round down
43 becomes 40
143 becomes 140
1433 becomes 1430

Round up
43 becomes 50
143 becomes 150
1433 becomes 1440

我遇到的价格范围是:
£143 - £193

我想显示为:
£140 - £200

因为看起来更干净

关于如何实现此目标的任何想法?

最佳答案

我将创建几个方法;

int RoundUp(int toRound)
{
     if (toRound % 10 == 0) return toRound;
     return (10 - toRound % 10) + toRound;
}

int RoundDown(int toRound)
{
    return toRound - toRound % 10;
}

模数为我们提供余数,在四舍五入的情况下,10 - r将您带到最接近的十分之一,在四舍五入时,您只需减去r。非常简单。

10-08 16:19