在JavaScript中以20(或X)的步长舍入? [英] Rounding in steps of 20 (or X) in JavaScript?
本文介绍了在JavaScript中以20(或X)的步长舍入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数字从50开始到190结束。步骤是alwyas 20 - >
I have numbers starting at 50 and ending with 190. The steps are alwyas 20 -->
50,70,90,.... 190
现在我从一个文本字段中得到一个数字,必须根据这个舍入。因此,如果我得到55,它应该变为70,如果我得到77,它应该是90.如果我得到90,它当然应该保持90.我知道如何做到10步:
Now I get a number from a text filed which has to be rounded according to this. So if I get 55, it should become 70, if I get 77, it should be 90. If I get 90, it should of course stay 90. I know how to do it steps of 10:
// 55 --> 60
number = Math.ceil(number / 10) * 10
如何围绕数字我使用20步?
How to round the number I get using steps of 20?
谢谢!
推荐答案
如果你想以x为增量进行舍入,带偏移量:
If you want to round in increments of x, with an offset:
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
这篇关于在JavaScript中以20(或X)的步长舍入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文