Three ways to summarize JavaScript numeric conversions

  • 2020-03-30 03:37:13
  • OfStack

In JavaScript, there are generally three ways to convert values:

Number(param) function: param can be used for any data type

1.1 param is a Boolean value. True and false are converted to 1 and 0, respectively.

1.2 param is a value that is simply passed in and returned

1.3 param is null and undefined, returning 0 and NaN, respectively

1.4 param is a string that follows the following rules:

1.4.1 if the string contains only digits, the string is converted to decimal and the leading 0 is ignored.

1.4.2 if the string contains a valid floating point number format, the corresponding floating point value is returned, and the leading 0 is ignored;

1.4.3 returns a decimal value of equal size if the string contains valid hexadecimal values

1.4.4 returns 0 if the string is empty

1.4.5 NaN is returned if the string contains characters other than the above format

1.5 if the param is an object, it calls the valueOf() method, converts the return string value according to the previous rule, and if NaN is returned, it calls the toString() method, again converts the return string value according to the previous rule.

1.6 the sample:


<span style="font-family:Microsoft YaHei;font-size:18px;">var num1 = Number("hello"); //NaN 
var num2 = Number(""); //0 
var num3 = Number("00022"); //22 
var num4 = Number(true); //1</span>

ParseInt (param) : converts a string to an integer. Param is a string type.

ParseIFloat (param) : converts a string to a floating point number. Param is a string type.

Like parseInt, parseFloat() parses from the first character until all characters are parsed or a non-floating point character is encountered. The first decimal point is valid, but the second is not, and the function can only parse decimal Numbers because it always ignores the leading 0.


<span style="font-family:Microsoft YaHei;font-size:18px;">var num1 = parseFloat("1234blue"); // 1234 
var num2 = parseFloat("0xf6"); // 0 
var num3 = parseFloat("22.5"); // 22.5 
var num4 = parseFloat("22.5.4"); //22.5 
var num5 = parseFloat("3.125e7"); // 31250000</span>

Related articles: