Home >Web Front-end >JS Tutorial >How to convert value to int type in javascript
In JavaScript, you can use the parseInt() method to convert the value to the int type. This method can convert the value to an integer. The syntax format is "parseInt(string,radix)". This method will first parse the character at position 0, and if it is not a valid number, it will directly return NaN.
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
javascript converts the value to the int type
In javascript, you can use the parseInt() method to convert the value to the int type. The syntax is as follows:
parseInt(string, radix)
Description | |
---|---|
Required. The string to be parsed. | |
Optional. Represents the base of the number to be parsed. The value is between 2 ~ 36. |
The conversion process is as follows:
console.log(parseInt("123abc")); //返回数字123 console.log(parseInt("1.73")); //返回数字1 console.log(parseInt(".123")); //返回值NaNDots in floating point numbers are illegal characters for parseInt(), so the decimal part of the value will not be converted. If it is a numeric string starting with 0, parseInt() will treat it as an octal number: first convert it to an octal value, and then convert it to a decimal number and return it. If it is a numeric string starting with 0x, parseInt() will treat it as a hexadecimal number: first convert it to a hexadecimal value, and then convert it to a decimal number and return .
var d = 010; //八进制数字字符串 var e = 0x10; //十六进制数字字符串 console.log(parseInt(d)); //返回十进制数字8 console.log(parseInt(e)); //返回十进制数字16parseInt() also supports base mode, which can convert digital strings in different bases such as binary, octal, and hexadecimal into integers. The base mode is specified by the second parameter of the parseInt() function.
Example:
//把十六进制数字字符串“123abc”转换为十进制整数 var a = "123abc"; console.log(parseInt(a,16)); //返回十进制整数1194684 //把二进制、八进制和十进制数字字符串转换为十进制的整数 console.log(parseInt("10",2)); //把二进制数字 10 转换为十进制整数,为 2 console.log(parseInt("10",8)); //把八进制数字 10 转换为十进制整数,为 8 console.log(parseInt("10",10)); //把十进制数字 10 转换为十进制整数,为 10[Recommended learning:
javascript advanced tutorial]
The above is the detailed content of How to convert value to int type in javascript. For more information, please follow other related articles on the PHP Chinese website!