Javascript Math.floor 와 parseInt 차이점
설명
Javascript 함수 중에 Math.floor와 parseInt 2가지 모두 역할이 비슷해서 헷깔립니다.
2개의 함수의 차이점을 알아보도록 하겠습니다.
▶설명
Math.floor
참고 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
Math.floor() - JavaScript | MDN
The Math.floor() static method always rounds down and returns the largest integer less than or equal to a given number.
developer.mozilla.org
Math.floor 함수의 설명을 보면 항상 소수점을 내림한다고 나옵니다.
parseInt
참고 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
parseInt() - JavaScript | MDN
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
developer.mozilla.org
parseInt 함수는 정수로 반환해주는 함수입니다.
▶차이점
Math.floor 와 parseInt 모두 소수점을 없애는 것은 동일합니다. 그러면 차이점은 무엇일까요?
간단한 예시를 통해 확인해보도록 하겠습니다.
양수
Math.floor(3.14) // 3
Math.floor(15.29) // 15
Math.floor(2003.777) // 2003
parseInt(3.14) // 3
parseInt(15.29) // 15
parseInt(2003.777) // 2003
아래는 크롬 개발 도구의 콘솔에서 실행한 결과입니다.
크롬 개발자 도구의 콘솔에서 실행한 결과
양수일 경우 2개의 함수의 결과는 동일하게도 소수점을 버린 정수 값이 오는 것을 확인할 수 있습니다.
차이점은 음수의 경우 발생합니다.
음수
Math.floor(-3.14) // -4
Math.floor(-15.29) // -16
Math.floor(-2003.777) // -2004
parseInt(-3.14) // -3
parseInt(-15.29) // -15
parseInt(-2003.777) // -2003
아래는 크롬 개발 도구의 콘솔에서 실행한 결과입니다.
크롬 개발자 도구의 콘솔에서 실행한 결과
parseInt의 경우 소수점 버리는 것으로 끝이지만, Math.floor 는 소수점을 내림 했기 때문에 값이 다른 것을 알 수 있습니다.