对不起标题,在标题中很难解释这个问题。
因此,我想将数字四舍五入到最接近的小数位/因数(总是向上),或者将其在文本字段中添加时如何调用。我想使用javascript来做到这一点,但可能找不到为此的函数或示例,但我希望此解决方案有一个函数?
示例:
Scale/factor = 12
User enters the number 3 , the number should change into 12
User enters the number 25, the number should change into 36
User enters the number 47, the number should change into 48
答案 0 :(得分:1)
只需将Math.ceil
的除法结果四舍五入并乘以您的因数即可:
const factor = 12;
Math.ceil(47 / factor) * factor; // 48
Math.ceil(25 / factor) * factor; // 36
答案 1 :(得分:0)
您似乎想要使用Math.ceil
的高阶函数:
const makeTransform = scale => num => Math.ceil(num / scale) * scale;
const transform12 = makeTransform(12);
console.log(transform12(3));
console.log(transform12(25));
console.log(transform12(47));
答案 2 :(得分:0)
这是不涉及浮点数的解决方案:
function stickTo (factor, num) {
const rest = num % factor;
if (rest) {
return num + factor - rest;
}
return num
}
// stickTo(12, 3) --> 12
// stickTo(12, 25) --> 36
// stickTo(12, 47) --> 48
// stickTo(12, 12) --> 12