在 JavaScript 中如何四舍五入到整数?

我有下面的代码来计算一定的百分比:

var x = 6.5;
var total;


total = x/15*100;


// Result  43.3333333333

我想要的结果是确切的数字 43,如果总数是 43.5,它应该四舍五入到 44

有没有办法在 JavaScript 中实现这一点?

109975 次浏览

Use the Math.round() function to round the result to the nearest integer.

//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

Use Math.round to round the number to the nearest integer:

total = Math.round(x/15*100);
total = Math.round(total);

Should do it.

a very succinct solution for rounding a float x:

x = 0|x+0.5

or if you just want to floor your float

x = 0|x

this is a bitwise or with int 0, which drops all the values after the decimal