JavaScript

Number() vs parseInt()

Yuclid 2020. 11. 16. 21:04

나는 문자열을 숫자로 바꾸는 함수는 parse시리즈만 있는 줄 알았는데

이번에 강의를 보면서 Number()도 있다는 것을 알게되었고

그러면서 이게 무슨 차이가 있을까? 라는 의문이 들어서 알아보았다

Number()

const str = '1000';
const str1 = '1000원';
const str2 = '약1000원';

console.log(Number(str));
console.log(Number(str1));
console.log(Number(str2));

Number를 사용할 경우 문자열에 숫자로 변환할 수 없는 문자가 끼어있으면 NaN을 반환한다

parseInt()

const str = '1000';
const str1 = '1000원';
const str2 = '약1000원';

console.log(parseInt(str));
console.log(parseInt(str1));
console.log(parseInt(str2));

parseInt는 변환할 수 없는 문자열이 나올 때 까지 일단 숫자로 변환하고 본다