How JavaScript converts data into Integers
This article mainly introduces how JavaScript converts data into integers. If you need it, refer to it.
JavaScript provides the parseInt method to convert a value to an integer, which is used to convert the string data to "123" or a floating point number of 1.23.
The Code is as follows:
ParseInt ("1"); // 1
ParseInt ("1.2"); // 1
ParseInt ("-1.2"); //-1
ParseInt (1.2); // 1
ParseInt (0); // 0
ParseInt ("0"); // 0
However, this parseInt function is not often valid:
The Code is as follows:
ParseInt ('06'); // 6
ParseInt ('08'); // 0 note that the new version of Google has been fixed
ParseInt ("1g"); // 1
ParseInt ("g1"); // NaN
Therefore, I wrote a function to convert any data into integers.
The Code is as follows:
Function toInt (number ){
Return number * 1 | 0 | 0;
}
// Test
ToInt ("1"); // 1
ToInt ("1.2"); // 1
ToInt ("-1.2"); //-1
ToInt (1.2); // 1
ToInt (0); // 0
ToInt ("0"); // 0
ToInt (Number. NaN); // 0
ToInt (1/0); // 0
Here are some conversion functions written by netizens, which can also be used as a reference to convert data into integers.
The Code is as follows:
Function toInt (number ){
Return number & + number | 0 | 0;
}
Note that the valid Integer Range of the preceding two functions in Javascript is-1569325056 ~ 1569325056
To express a larger range of values in js, I also wrote a function for reference, as shown below:
The Code is as follows:
Function toInt (number ){
Return Infinity = number? 0: (number * 1 | 0). toFixed (0) * 1;
}