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
这怎么可能?
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
演示在这里:
用户Math.ceil()
功能围捕一些。
Math.floor()
- 圆整。
var number = 0.08;
var newNumber = Math.ceil($scope.newAmt * 4)/4 //round to nearest .25
你可能希望我们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
添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
你拼错了我的名字,但这值得赞扬+1 –
道歉,纠正它:) –
最大的问题是你使用
Math.round($scope.newAmt * 4)/4
这将始终一轮的基础上取整,因为我们知道它的标准方式。你可以使用
Math.ceil($scope.newAmt * 4)/4
因为这将总是四舍五入。这是下舍入兄弟是
Math.floor()
顺便说一句。
你只会处理高达2DP的数字吗? – Toastrackenigma