This article mainly introduces the way JavaScript converts data into integers, and friends who need it can refer to the
JavaScript provides a way to convert a numeric value to an integer, parseint the string data "123", or floating-point number 1.23. 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 always valid: code is as follows: parseint (' 06 '); 6 parseint (' 08 '); 0 Note that Google has revised the new version of parseint ("1g"); 1 parseint ("G1"); NaN For this reason, I wrote a function to convert arbitrary data into integers. 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 Here also has the user writes the transformation function, also notes down provides the reference, equally is suitable transforms the data to the integer. The code is as follows: function ToInt (number) { return number && + number | 0 | | 0; Note that the above two function JS can represent an integer valid range of -1569325056 ~ 1569325056 In order to express a larger range of values in JS, I also wrote a function to provide reference, as follows: Code is as follows: function ToInt (number) { return Infinity = = number? 0: (number*1 | | 0). toFixed (0) *1; }