如何在 JavaScript 中四舍五入为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6968042/
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
How can I round to whole numbers in JavaScript?
提问by idontknowhow
I have the following code to calculate a certain percentage:
我有以下代码来计算某个百分比:
var x = 6.5;
var total;
total = x/15*100;
// Result 43.3333333333
What I want to have as a result is the exact number 43
and if the total is 43.5
it should be rounded to 44
结果我想要的是确切的数字43
,如果总数是43.5
它应该四舍五入到44
Is there way to do this in JavaScript?
有没有办法在 JavaScript 中做到这一点?
回答by hmakholm left over Monica
Use the Math.round()
function to round the result to the nearest integer.
使用该Math.round()
函数将结果四舍五入到最接近的整数。
回答by Drake
//method 1
Math.ceil(); // rounds up
Math.floor(); // rounds down
Math.round(); // does method 2 in 1 call
//method 2
var number = 1.5; //float
var a = parseInt(number); // to int
number -= a; // get numbers on right of decimal
if(number < 0.5) // if less than round down
round_down();
else // round up if more than
round_up();
either one or a combination will solve your question
一个或一个组合将解决您的问题
回答by Phil
total = Math.round(total);
Should do it.
应该做。
回答by Gumbo
Use Math.round
to round the number to the nearest integer:
用于Math.round
将数字四舍五入到最接近的整数:
total = Math.round(x/15*100);
回答by Karo Castro-Wunsch
a very succinct solution for rounding a float x:
用于舍入浮点数 x 的一个非常简洁的解决方案:
x = 0|x+0.5
x = 0|x+0.5
or if you just want to floor your float
或者如果你只是想把你的浮子放在地板上
x = 0|x
x = 0|x
this is a bitwise or with int 0, which drops all the values after the decimal
这是按位或 int 0,它删除小数点后的所有值