var number = 0.08;
var newNumber = Math.round(number * 4) / 4 //round to nearest .25
使用上面的代码,我可以舍入到最接近的.25。但是我只想把它整理一下。因此:
0.08 = 0.25
0.22 = 0.25
0.25 = 0.25
0.28 = 0.5
怎么可能呢?
你实际想要做的是取输入的上限,但不是在整数上操作,而是希望它在四分之一上运行。我们可以在这里使用的一个技巧是将输入乘以4以使其成为整数,然后将其置于JavaScript的Math.ceil()
函数中。最后,将结果除以4,使其恢复到逻辑上原始的开始。
使用此公式:
Math.ceil(4 * num) / 4
function getCeiling(input) {
return Math.ceil(4 * input) / 4;
}
console.log("input: 0.08, output: " + getCeiling(0.08));
console.log("input: 0.22, output: " + getCeiling(0.22));
console.log("input: 0.25, output: " + getCeiling(0.25));
console.log("input: 0.28, output: " + getCeiling(0.28));
你可能想要我们Math.ceil()
:
ceil()
将数字向上舍入到其最接近的整数。
console.log(Math.ceil(0.08 * 4) / 4); // 0.25
console.log(Math.ceil(0.22 * 4) / 4); // 0.25
console.log(Math.ceil(0.25 * 4) / 4); // 0.25
console.log(Math.ceil(0.28 * 4) / 4); // 0.5
Tim Biegeleisen绝对是最好的答案,但是如果你想要一个更“简单”的方法,你基本上可以编写自己的函数,例如:
var round = (num) => {
if (num <= 0.25) {
return 0.25;
} else if (num > 0.25 && num <= 0.5) {
return 0.5;
} else if (num > 0.5 && num <= 0.75) {
return 0.75;
} else if (num > 0.75 && num <= 1.0) {
return 1.0;
} else {
return null;
}
};
调用时,它将重现您想要的结果:
round(0.08); // 0.25
round(0.22); // 0.25
round(0.25); // 0.25
round(0.28); // 0.5
用户Math.ceil()
函数来舍入一个数字。
Math.floor()
- 向下舍入。
var number = 0.08;
var newNumber = Math.ceil($scope.newAmt * 4) / 4 //round to nearest .25
最大的问题是你使用
Math.round($scope.newAmt * 4) / 4
这将始终基于我们所知的标准舍入方式进行舍入。你可以用
Math.ceil($scope.newAmt * 4) / 4
因为这将永远围绕。这是下来的兄弟是
Math.floor()
顺便说说。