Several methods of converting string type to number type

1. Number()

var str1="11",
    str2="hello",
	num1 = Number( str1 ),
    num2 = Number( str2 );
console.log(num1);
console.log(num2);
//结果为:11 NAN

2.parseInt()

If the first string is not a number, NaN is returned.

If it is a number with a decimal, it will be removed.

var str1="HELLO",
	str2="123HELLO",
	str3="123.33.3HELLO";
str1 = parseInt( str1 );
str2 = parseInt( str2 );
str3 = parseInt( str3 );
console.log(str1);
console.log(str2);
console.log(str3);
//结果:NaN 123 123

3.parseFloat()

If it is a number with a decimal point, it will be retained, but only the number after the first decimal point will be retained.

var str1="HELLO",
	str2="123HELLO",
	str3="123.33.3HELLO";
str1 = parseFloat( str1 );
str2 = parseFloat( str2 );
str3 = parseFloat( str3 );
console.log(str1);
console.log(str2);
console.log(str3);
//结果: NaN 123 123.33

4.new Number()

Generally not recommended.

num = new Number( str ).valueOf();
	console.log(num.valueOf());

5   *  /

num1 = str / 1;
	num2 = str * 1;
	console.log( num1 + ' 的类型为 ' + typeof num1 );
	console.log( num2 + ' 的类型为 ' + typeof num2 );

Guess you like

Origin blog.csdn.net/qq_52421092/article/details/125070117