javascript总是舍入到大数 [英] javascript round always to upper number
本文介绍了javascript总是舍入到大数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望我的数字总是四舍五入到这样的闭数上限:
I want my number to always get rounded to the closes upper number like this:
1.2 => 2
1.4 => 2
2.5 => 3
2.9 => 3
我该如何使用JavaScript?
How can i do this with JavaScript?
推荐答案
您可以使用Math.ceil()
函数.
You can use the Math.ceil()
function.
Math.ceil(1.1) // returns 2
相反,如果您想舍入 ,则可以使用Math.floor()
Conversely, if you wanted to round down you'd use Math.floor()
Math.floor(1.8) // returns 1
这是一个演示:
console.table([1, 1.25, 1.49, 1.5, 1.75, 2].map(n => ({
n,
["Math.floor(n)"]: Math.floor(n),
["Math.ceil(n)"]: Math.ceil(n),
["Math.round(n)"]: Math.round(n),
})));
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script><script>console.config({maximize:true,timeStamps:false})</script><style>.as-console-wrapper{display:block;}</style>
注意:地板和天花板功能并非javascript独有.有关更多信息,请参见维基百科条目.
这篇关于javascript总是舍入到大数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文