7

我的数字从 50 开始,以 190 结束。步骤总是 20 -->

50, 70, 90, .... 190

现在我从一个必须根据这个四舍五入的文本文件中得到一个数字。所以如果我得到 55,它应该变成 70,如果我得到 77,它应该是 90。如果我得到 90,它当然应该保持 90。我知道如何做到 10 步:

// 55 --> 60
number = Math.ceil(number / 10) * 10

如何四舍五入我使用 20 步得到的数字?

谢谢!

4

4 回答 4

23

如果要以 x 为增量进行舍入,并带有偏移量:

function round(number, increment, offset) {
    return Math.ceil((number - offset) / increment ) * increment + offset;
}
round(51,  20, 10) // 70
round(70,  20, 10) // 70
round(99,  20, 10) // 110
round(100, 20, 10) // 110
于 2013-01-31T14:14:22.150 回答
3
function round(number,x,o) {
 o = ~~(o);
   return o + Math.ceil((number - o)/ x ) * x 
 }
 console.log(round (55,20,10)) //70
 console.log(round (77,20,10)) //90
 console.log(round (90,20,10)) //90

@Cerbrus thx 指出这一点

于 2013-01-31T14:08:10.940 回答
1

也许有类似的东西

number = Math.ceil( (number - 50) / 20 ) * 20 + 50;
于 2013-01-31T14:05:49.753 回答
1
var number;
var a =number-10-((number-10)%20);
var result=a+30;
// does not work if num is 70 or 90 so
if(result-20==number)
Result=number;

或作为单行:

var result=number+20-((number-10)%20) - result-20==number : 0 ? 20;

The logic is that first, you add 20 to the number. Take the number 77. 77+20=97. But, 77+20-7=90, what you want. And 7 is the difference between 77 and 70, the previous valid number. You can get the differencewith (number-10)%20. However, it doesn't work if number is OK to start out with, hence the logic at the end.

于 2013-01-31T14:15:48.170 回答