Javascript method to convert a value into an int type: 1. Use the "parseInt(value)" method to convert a value into an int integer; 2. Use "Math.floor(value)", "Math.ceil (value)" and "Math.round(value)" methods convert decimal values into int integers.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: Use parseInt()
parseInt() is a global method that converts a value to an integer. The conversion process is as follows:
First parse the character at position 0. If it is not a valid number, NaN will be returned directly.
If the character at position 0 is a number or can be converted to a valid number, continue to parse the character at position 1. If it is not a valid number, return the valid character at position 0 directly. number.
And so on, analyzing each character one by one from left to right until a non-numeric character is found.
parseInt() will convert all previously analyzed legal numeric characters into numerical values and return them.
1 2 3 |
|
Dots in floating-point numbers are illegal characters for parseInt(), so the decimal part of the value will not be converted.
If it is a numeric string starting with 0, parseInt() will treat it as an octal number: first convert it to an octal value, and then convert it to a decimal number and return it.
If it is a numeric string starting with 0x, parseInt() will treat it as a hexadecimal number: first convert it to a hexadecimal value, and then convert it to a decimal number and return .
1 2 3 4 |
|
Method 2: Use Math.floor(), Math.ceil(), Math.round() to convert decimals to integers
There are 3 Math objects Static functions can be rounded
Math.floor(): Returns the largest integer less than the parameter value.
Math.ceil(): Returns the smallest integer greater than the parameter value.
Math.round(): Rounding.
Example 1: The following code simply compares the values of these three methods
1 2 3 4 5 6 7 |
|
Example 2: The following code combines Math.floor() and Math.ceil( ) method, use JavaScript to design a function that rounds numbers
1 2 3 4 5 6 |
|
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to convert value to int type in javascript. For more information, please follow other related articles on the PHP Chinese website!