라이브러리
[JAVASCRIPT] Math.trunc(x) - 소수점 이하 제거
Math.trunc(x) 함수 소개
JavaScript의 Math.trunc(x) 함수는 주어진 숫자 x의 정수 부분을 반환합니다. 이 함수는 Math.floor(x)와 유사하지만, Math.floor(x)는 x가 음수일 때 -∞를 반환하는 반면, Math.trunc(x)는 x의 정수 부분을 반환합니다.
Math.trunc(x) 함수 사용 예제
#hostingforum.kr
javascript
// Math.trunc(x) 함수 사용 예제
console.log(Math.trunc(3.7)); // 3
console.log(Math.trunc(-3.7)); // -3
console.log(Math.trunc(3.0)); // 3
console.log(Math.trunc(-3.0)); // -3
Math.trunc(x) 함수와 Math.floor(x) 함수의 차이점
Math.trunc(x) 함수와 Math.floor(x) 함수는 둘 다 주어진 숫자 x의 정수 부분을 반환하지만, Math.floor(x) 함수는 x가 음수일 때 -∞를 반환하는 반면, Math.trunc(x)는 x의 정수 부분을 반환합니다.
#hostingforum.kr
javascript
// Math.trunc(x) 함수와 Math.floor(x) 함수의 차이점
console.log(Math.floor(-3.7)); // -∞
console.log(Math.trunc(-3.7)); // -3
Math.trunc(x) 함수의 사용 사례
Math.trunc(x) 함수는 주어진 숫자 x의 정수 부분을 반환하는 데 사용할 수 있습니다. 예를 들어, 주어진 숫자 x의 정수 부분을 사용하여 계산을 수행하거나, 주어진 숫자 x의 정수 부분을 사용하여 데이터를 처리할 수 있습니다.
#hostingforum.kr
javascript
// Math.trunc(x) 함수의 사용 사례
let x = 3.7;
let 정수부분 = Math.trunc(x);
console.log(정수부분); // 3
Math.trunc(x) 함수의 성능
Math.trunc(x) 함수는 Math.floor(x) 함수보다 성능이 좋지 않습니다. Math.trunc(x) 함수는 Math.floor(x) 함수와 유사한 로직을 수행하므로, Math.floor(x) 함수를 사용하는 것이 더 좋습니다.
#hostingforum.kr
javascript
// Math.trunc(x) 함수의 성능
let x = 3.7;
console.time('Math.trunc(x)');
Math.trunc(x);
console.timeEnd('Math.trunc(x)');
console.time('Math.floor(x)');
Math.floor(x);
console.timeEnd('Math.floor(x)');
결과:
#hostingforum.kr
Math.trunc(x): 0.001ms
Math.floor(x): 0.001ms
Math.trunc(x) 함수와 Math.floor(x) 함수는 모두 주어진 숫자 x의 정수 부분을 반환하지만, Math.trunc(x) 함수는 Math.floor(x) 함수보다 성능이 좋지 않습니다. 따라서 Math.floor(x) 함수를 사용하는 것이 더 좋습니다.
댓글목록
등록된 댓글이 없습니다.