JS has 3 functions to convert non-numeric values into values: Number (), parseint (), and parsefloat ().
Number () can be used for any data type, while the other two functions are specifically used to convert a string to a numeric value. These three functions will return different results for the same input.
The conversion rules for the number () function are as follows:
- If it is a Boolean value, it is converted to 1 or 0.
- If it is a number, simply pass in the outgoing.
- If NULL, 0 is returned.
- If it is undefined, return nan.
- If it is a string, if the string contains non-numeric characters, it is converted to Nan.
- If it is an object, call the object's valueof (), then return the value according to the preceding rule, if the conversion result is Nan, call the object's ToString () method, and then convert the returned string value again according to the previous rule.
Because the number () function is more complex and unreasonable when converting strings, parseint () is more commonly used when working with integers. It is more to see if it conforms to the numeric pattern when converting a string. It ignores the spaces in front of the string until the first non-whitespace character is found. If the first character is not a numeric character or symbol, parseint () returns Nan, that is, converting an empty string with parseint () also returns Nan. If the first character is a numeric character, it continues to parse the second character until all subsequent characters have been resolved or the first non-numeric character is encountered. For example, "100px" will be converted to 100. "22.5" is converted to 22 because the decimal point is not a valid numeric character.
Parsefloat is almost the same as parseint, except that it can parse decimals.
numeric conversion of JavaScript