JavaScript provides a method of converting numerical values to PARSEINT for converting the string data "123", or the number of floating points 1.23.
Copy code code as follows:
Parseint ("1"); // 1
Parseint ("1.2"); // 1
Parseint ("-1.2"); // -1
Parseint (1.2); // 1
Parseint (0); // 0
Parseint ("0"); // 0
But this PARSEINT function is not often effective:
Copy code code as follows:
Parseint ('06 '); // 6
Parseint ('08 '); // 0 Note, Google's new version has been revised
Parseint ("1g"); // 1
Parseint ("g1"); // nan
To this end, I wrote a function to convert any data into an integer.
Copy code code 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
There are also conversion functions written by netizens here, which are also written down to provide reference, which is also suitable for converting data into integer.
Copy code code as follows:
Function Toint (Number) {
Return number && + number | 0 || 0;
}
Note that the effective range of the integer of the above two functions JS is -1569325056 ~ 1569325056
In order to express a larger range in JS, I also wrote a function to provide a reference, as follows:
Copy code code as follows:
Function Toint (Number) {
Return infinity === Number? 0: (Number*1 || 0) .tofixed (0)*1;
}