
자바스크립트에서 숫자를 다룰 때 유용한 Math 객체의 메서드들이 많이 있습니다. 이번 글에서는 Math.floor(), Math.round(), Math.random() 등의 대표적인 Math 메서드들을 정리해보겠습니다.
Math.floor() 메서드는 숫자를 가장 가까운 아래 정수로 내립니다.
console.log(Math.floor(4.9)); // 4
console.log(Math.floor(4.1)); // 4
console.log(Math.floor(-4.9)); // -5
Math.round() 메서드는 소수점 이하를 반올림하여 가장 가까운 정수로 변환합니다.
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.4)); // 4
console.log(Math.round(-4.5)); // -4
Math.ceil() 메서드는 숫자를 가장 가까운 위 정수로 올립니다.
console.log(Math.ceil(4.1)); // 5
console.log(Math.ceil(4.9)); // 5
console.log(Math.ceil(-4.1)); // -4
Math.random() 메서드는 0 이상 1 미만의 랜덤한 실수를 반환합니다.
console.log(Math.random()); // 예: 0.35215641235
console.log(Math.random()); // 예: 0.9876543210
const randomInt = Math.floor(Math.random() * 10) + 1;
console.log(randomInt); // 1~10 사이의 랜덤 정수
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(5, 15)); // 5~15 사이의 랜덤 정수
Math.trunc() 메서드는 숫자의 소수점 이하를 잘라내고 정수 부분만 반환합니다.
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.9)); // -4
Math.floor()와 비슷하지만 음수일 때는 내리지 않고 그냥 소수점을 제거합니다.Math.abs() 메서드는 숫자의 절댓값(양수)만 반환합니다.
console.log(Math.abs(-10)); // 10
console.log(Math.abs(5)); // 5
Math.pow(x, y) 메서드는 x의 y제곱을 계산합니다.
console.log(Math.pow(2, 3)); // 8 (2의 3제곱)
console.log(Math.pow(5, 2)); // 25
Math.sqrt() 메서드는 숫자의 제곱근을 반환합니다.
console.log(Math.sqrt(16)); // 4
console.log(Math.sqrt(25)); // 5
자바스크립트 Math 객체의 다양한 메서드를 활용하면 숫자를 다루는 데 매우 유용합니다. 특히 Math.floor(), Math.round(), Math.random() 등은 실전에서 자주 쓰이므로 꼭 익혀두세요!
추가로 궁금한 점이 있으면 댓글로 남겨주세요! 😊