JS numeric conversion
JS numerical conversion methods are four kinds: Number (), parseInt (), parseFloat (), or data type * 1/1.
Their difference is:
1.Number (): can be converted to non-numerical values
If the Boolean value, true and flase are converted to 0 to 1 and
If it is digital, it is a simple pass and return
If the value is null, then return 0
If it is undefined, NaN is returned
console.log(Number(true));//1 console.log(Number(false));//0 console.log(Number(10));//10 console.log(Number(null));//0 console.log(Number(undefined));//NaN
If a string, then there are the following rules:
If the string contains only digits, it is converted to decimal, that is, "1" becomes 1, "123" into 123, and "011" will be changed to 11 (note that this will not be handled as octal)
If the string contains a valid hexadecimal format, such as "1.1", it is converted to floating point values corresponding
If the string contains a valid hexadecimal format, for example, "0xf", it will convert to a decimal integer which is the same size.
If the string is empty, it is converted into 0
If the character string contains a format other than the above, it is converted to NaN
console.log(Number("1"));//1 console.log(Number("012"));//12 console.log(Number("0o10"));//8 console.log(Number("0b111"));//7 console.log(Number("3.14"));//3.14 console.log(Number("0xf"));//15 console.log(Number(""));//0 console.log(Number("123Hello"));//NaN
2.parselnt (): is a non-numeric value into
Compared number0 function, parselnt0 to see if there will be more digital, there will be converted to a number.
The simplest example is when the number (function converts "123Hello" converted to NaN, while parselnt0 it will be converted to an empty string 123. encountered, number (function converts to 0, and will be parselnt0 which is converted to NaN. Finally, when it encounters a decimal, there will be a rounding process. For example, "3.14" is converted to "3"
console.log(parseInt("1"));//1 console.log(parseInt("012"));//12 console.log(Number("0o10"));//8 console.log(Number("0b111"));//7 console.log(parseInt("3.14"));//3 console.log(parseInt("0xf"));//15 console.log(parseInt(""));//NaN console.log(parseInt("123Hello"));//123
3.parseFloat (): non floating point value into
parseFloat0 parse only decimal values, there is no second argument, the function will be converted with a string decimal decimal point. If no point number is converted to an integer. The same parseFloat () also convert more value as possible,
console.log(parseFloat("21"));//21 console.log(parseFloat("123Hello"));//123 console.log(parseFloat("0xA"));//0 console.log(parseFloat("3.14"));//3.14 console.log(parseFloat("22.34.5"));//22.34 console.log(parseFloat("0908.34"));//908.34 console.log(parseFloat("3.1415e2"));//314.15
4. Data type or * 1/1