JS method of taking integers: 1. Use the "Math.trunc()" method to remove the decimal part of the number and keep the integer part; 2. Use the "Math.round()" method to return a rounded number. The integer part; 3. Round up and so on through the "Math.ceil()" method.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
JavaScript performs numerical rounding:
1. Math.trunc()
1. Definition
Math.trunc( ) method removes the decimal part of a number and retains the integer part.
2. Grammar
Math.trunc(value)
3. Example
console.log(Math.trunc(2.01)); // 2 console.log(Math.trunc(2.9)); // 2 console.log(Math.trunc('0.22')); // 0 console.log(Math.trunc(-1.22)); // -1 console.log(Math.trunc(-1.56)); // -1 console.log(Math.trunc(true)); // 1 console.log(Math.trunc(undefined)); // NaN
2. Math.round()
1. Definition
Math. The round() method returns the rounded integer part of a number.
2. Syntax
Math.round(value)
3. Example
console.log(Math.round(2.01)); // 2 console.log(Math.round(2.9)); // 3 console.log(Math.round('0.22')); // 0 console.log(Math.round(-1.22)); // -1 console.log(Math.round(-1.56)); // -2 console.log(Math.round(true)); // 1 console.log(Math.round(undefined)); // NaN
3. Math.ceil()
1. Definition
Math. The ceil() method returns the smallest integer that is greater than or equal to the number, that is, rounded up.
2. Syntax
Math.ceil(value)
3. Example
console.log(Math.ceil(2.01)); // 3 console.log(Math.ceil(2.9)); // 3 console.log(Math.ceil('0.22')); // 1 console.log(Math.ceil(-1.22)); // -1 console.log(Math.ceil(-1.56)); // -1 console.log(Math.ceil(true)); // 1 console.log(Math.ceil(undefined)); // NaN
4. Math.floor()
1. Define the
Math.floor() method to return the smallest integer that is less than or equal to a number, that is, rounded down.
2. Grammar
Math.floor(value)
3. Example
console.log(Math.floor(2.01)); // 2 console.log(Math.floor(2.9)); // 2 console.log(Math.floor('0.22')); // 0 console.log(Math.floor(-1.22)); // -2 console.log(Math.floor(-1.56)); // -2 console.log(Math.floor(true)); // 1 console.log(Math.floor(undefined)); // NaN
[Recommended learning: js basic tutorial】
The above is the detailed content of How to get an integer in js. For more information, please follow other related articles on the PHP Chinese website!