Home >Web Front-end >JS Tutorial >How to convert decimal to integer in javascript
JS method of converting decimals to integers: 1. Use the "parseInt (decimal value)" statement; 2. Use the "~~decimal value" statement; 3. Use "Math.floor (decimal value)" statement; 4. Use the "Math.ceil (decimal value)" statement; 5. Use the "Math.round (decimal value)" statement.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: Use parseInt()
The parseInt() function parses a string and returns an integer.
When the value of parameter radix is 0, or the parameter is not set, parseInt() will determine the base of the number based on string.
When the parameter radix is omitted, JavaScript defaults to the radix of numbers as follows:
If the string starts with "0x", parseInt() will parse the rest of the string into ten Hexadecimal integer.
If string starts with 0, then ECMAScript v3 allows an implementation of parseInt() to parse the following characters as octal or hexadecimal digits.
If string starts with a number from 1 to 9, parseInt() will parse it into a decimal integer.
Example: Use parseInt() to parse different strings
document.write(parseInt("10") + "<br>"); document.write(parseInt("10.33") + "<br>"); document.write(parseInt("34 45 66") + "<br>"); document.write(parseInt(" 60 ") + "<br>"); document.write(parseInt("40 years") + "<br>"); document.write(parseInt("He was 40") + "<br>"); document.write("<br>"); document.write(parseInt("10",10)+ "<br>"); document.write(parseInt("010")+ "<br>"); document.write(parseInt("10",8)+ "<br>"); document.write(parseInt("0x10")+ "<br>"); document.write(parseInt("10",16)+ "<br>");
Output results:
10 10 34 60 40 NaN 10 10 8 16 16
Method 2: Negate twice
var decimal=4; var integer = ~~decimal; // 4 = ~~4.123 console.log(integer);
Output result:
4
Method 3: Math.floor() round down
Math.floor(): Returns the largest integer less than the parameter value.
console.log(Math.floor(2.5)); //2 console.log(Math.floor(-2.5)); //-3
Method 4: Math.ceil() rounds up
Math.ceil(): Returns the smallest integer greater than the parameter value.
console.log(Math.ceil(2.5)); //3 console.log(Math.ceil(-2.5)); //-2
Method 5: Math.round() rounding
Math.round(): Rounding.
console.log(Math.round(2.5)); //3 console.log(Math.round(-2.5)); //-2 console.log(Math.round(-2.6)); //-3
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to convert decimal to integer in javascript. For more information, please follow other related articles on the PHP Chinese website!