Javascript 如何将数字四舍五入到最接近的比例/系数数字
很抱歉这个标题,在标题中解释这个问题有点困难 因此,我想将一个数字四舍五入到其最接近的比例/因子(始终向上),或者在文本字段中添加时如何调用它。我想用javascript实现这一点,但找不到函数或示例,但我希望有一个函数用于此解决方案 例如:Javascript 如何将数字四舍五入到最接近的比例/系数数字,javascript,Javascript,很抱歉这个标题,在标题中解释这个问题有点困难 因此,我想将一个数字四舍五入到其最接近的比例/因子(始终向上),或者在文本字段中添加时如何调用它。我想用javascript实现这一点,但找不到函数或示例,但我希望有一个函数用于此解决方案 例如: Scale/factor = 12 User enters the number 3 , the number should change into 12 User enters the number 25, the number should chan
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
只需使用
Math.ceil
除以并乘以因子的结果即可:
const factor = 12;
Math.ceil(47 / factor) * factor; // 48
Math.ceil(25 / factor) * factor; // 36
看起来您需要一个使用
Math.ceil
的高阶函数:
constmaketransform=scale=>num=>Math.ceil(num/scale)*scale;
const transform12=makeTransform(12);
控制台日志(12(3));
控制台日志(12(25));
控制台日志(12(47))代码>以下是一个不涉及浮动的解决方案:
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
可能重复的