js type conversion to digital type

Manually convert types to numeric types JS provides three methods:

Number(object);

parseInt(string, radix);

parseFloat(string, radix).

The specific usage of the three methods is shown in the following table:

Number(object)

method example return value illustrate
Number() Number(false) 0 If boolean, true and false are converted to 1 and 0 respectively
Number(3) 3 If it is a numeric value, return itself.
Number(new Date()) 3 Returns the number of milliseconds since January 1, 1970. .
Number(null) 0 If null, return 0.
Number(undefined) NaN If undefined, return NaN.
Number("123") 123 If the string contains only numbers, convert it to decimal (ignoring leading 0s)
Number("000.123") 0.123 If the string contains a valid floating point format, convert it to a floating point value (ignoring leading zeros)
Number("") 0 If it is an empty string, convert it to 0
Number("Hello word") NaN If the string contains a format other than the above, convert it to NaN

 

 parseInt(string, radix) 

method example return value illustrate
parseInt(string, radix):
If the radix parameter is specified, radix is ​​used as the base for parsing
parseInt(" Acura666") NaN Returns NaN if the first character is not a number sign
parseInt("666Acura") 666 If the first character is a number, continue parsing until the string is parsed or a non-numeric character is encountered
parseInt("22.6sss") 22 Convert to an integer, directly remove the decimal point and keep the integer
parseInt("11",2) 3

radix is ​​optional. Indicates the radix of the number to parse. The value is between 2 and 36.

If this parameter is omitted or its value is 0, the number will be parsed on a 10-base basis. If it starts with "0x" or "0X", it will be base 16.

If the argument is less than 2 or greater than 36, parseInt() will return NaN

 

parseFloat(string, radix)

method example return value illustrate
parseFloat(string, radix)
rules are basically the same as parseInt
parseFloat("0.0.000666Acura") 0 The first decimal point symbol is valid, parseFloat ignores all leading zeros
parseFloat("0.000666") 0.000666
parseFloat("0.2.000666") 0.2

I believe that you can clearly understand these three methods through the above three tables~~

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324924482&siteId=291194637