javascript 总是舍入到大数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11194831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript round always to upper number
提问by Linas
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
1.2 => 2
1.4 => 2
2.5 => 3
2.9 => 3
How can i do this with JavaScript?
我怎样才能用 JavaScript 做到这一点?
回答by canon
You can use the Math.ceil()
function.
您可以使用该功能。Math.ceil()
Math.ceil(1.1) // returns 2
Conversely, if you wanted to round downyou'd use Math.floor()
相反,如果你想四舍五入,你会使用Math.floor()
Math.floor(1.8) // returns 1
Here's a demo:
这是一个演示:
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>
Note: Floor and ceiling functions aren't exclusive to javascript. See this wikipedia entryfor more info.
注意:地板和天花板函数不是 javascript 独有的。有关更多信息,请参阅此维基百科条目。
回答by 0x499602D2
回答by Kh?i
Use Math.ceil()
用 Math.ceil()
It does exactly what you want.
它完全符合您的要求。
回答by Husniddin Qurbonboyev
I use Math.ceil()
function for round upper value.
我使用Math.ceil()
圆形上限值的函数。