Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The difference between parseInt() and Number() in JS


May 30, 2021 Article blog


Table of contents


Learning goals:

What are the differences between parseInt() and Number() when the two functions are most used to convert a string into a data type?

What to learn:

The parseInt() function resolves a given string to an integer at the specified cardinality. T he second parameter of parseInt (string, radix) represents the indent used, we generally use a 10-feed, or we may have a feed of 8 or 16. In order to avoid errors in parsing strings beginning with "0" and "0x", various javascript programming specifications state that the value of the second parameter must be explicitly given, such as parseInt ("123", 10).

parseInt('16', 8)  = 14
parseInt('10', 8)  = 8

parseInt('16', 10)  = 16
parseInt('10', 10)  = 10

parseInt('16', 16)  = 22
parseInt('10', 16)  = 16

ParseInt resolves string from scratch as an integer, returns the resolved integer portion when it encounters an unresolvable character, and returns the NaN directly if the first character cannot be resolved.

Number() can be used to perform type conversions without the new operator. I f it cannot be converted to a number, NaN is returned. Like "123a", parseInt() returns 123, Number() returns NaN, and different types of strings use the conversion differences of these two functions:

// 当字符串是由数字组成的时候 他们转换的数字一样的没有差别  
let numStr = '123'
console.log(parseInt(numStr))   //123
console.log(Number(numStr))		//123

// 当字符串是由字母组成的时候 
let numStr = 'abc'
console.log(parseInt(numStr))   //NaN
console.log(Number(numStr))		//NaN

// 当字符串是由数字和字母组成的时候 
let numStr = '123a'
console.log(parseInt(numStr))   //123
console.log(Number(numStr))		//NaN

// 当字符串是由0和数字
let numStr = '0123'
console.log(parseInt(numStr))   //123
console.log(Number(numStr))		//123

// **当字符串包含小数点**
let numStr = '123.456'
console.log(parseInt(numStr))		//123
console.log(Number(numStr))			//123.456

// **当字符串为null时**
let numStr = null
console.log(parseInt(numStr))		//NaN
console.log(Number(numStr))			//0

// **当字符串为''(空)时**
let numStr = ''
console.log(parseInt(numStr))		//NaN
console.log(Number(numStr))			//0

Summary of learning:

1. When strings are made up of numbers, the numbers they convert are the same, if the string does not contain numbers that are all letters, both methods simply return NaN results, and when strings are made up of 0s and numbers, all numbers except 0 are parsed;
2, when the string is composed of numbers and letters (1) letter at the beginning, both methods are only returned NaN result (2) letter is not at the beginning of the Number method returns NaN, pareseInt method returns data before the letter
3, parseInt for non-String type values to be converted to String type before action