Math 객체 메소드

지은·2022년 8월 23일
1

JavaScript

목록 보기
7/42

Math는 JavaScript의 내장 객체로 수학적 계산을 위한 여러 함수(메소드)들을 가지고 있다.

올림, 내림, 반올림

Math.ceil()

Math.ceil(num) : 무조건 올림하여 정수를 반환하는 함수

Math.ceil(0.01);  // 1
Math.ceil(7.01);  // 8
Math.ceil(-7.01); // -7

Math.floor()

Math.floor(num) : 무조건 내림하여 정수를 반환하는 함수

Math.floor(7.99);  // 7
Math.floor(7.01);  // 7
Math.floor(-7.01); // -8

Math.round()

Math.round(num) : 반올림하여 정수를 반환하는 함수

Math.round(7.5);  // 8
Math.round(-7.5); // -7

거듭제곱

Math.pow()

Math.pow(base, exponent) : baseexponent(지수)를 제곱한 값을 반환하는 함수

Math.pow(2, 4);   // 2⁴ = 16
Math.pow(16, 0.5) // √16 = 4

JavaScript에서 거듭 제곱하는 방법 3가지

1. num * num
2. num ** 2
3. Math.pow(num, 2)

절대값

Math.abs()

Math.abs(num) : 주어진 숫자의 절대값을 반환하는 함수

const num = -1.234;
Math.abs(num); // 1.234

랜덤한 수

Math.random()

Math.random() : 0 이상, 1 미만의 난수(랜덤한 숫자)를 반환한다.

Math.random(); // 0.9635763186332695
Math.random(); // 0.1702303742359248
Math.random(); // 0.6616192435243566

Math.random() * n : 0 이상, n 미만의 난수를 반환한다.

Math.random() * 10; // 1.162939655688744
Math.random() * 10; // 0.8674624303950695
Math.random() * 10; // 7.209699469880009
  • 정수로 된 난수를 구하고 싶다면 Math.floor() 메소드를 이용한다.
Math.floor(Math.random() * 10); // 1
Math.floor(Math.random() * 10); // 0
Math.floor(Math.random() * 10); // 7
  • 만약 0은 제외하고, n은 포함하여 1부터 n까지의 숫자 중 난수를 얻고 싶다면, 1을 더한다.
    ex) 1에서 10까지의 숫자 중 랜덤한 숫자
Math.floor(Math.random() * 10) + 1; // 10
Math.floor(Math.random() * 10) + 1; // 3
Math.floor(Math.random() * 10) + 1; // 1
profile
개발 공부 기록 블로그

0개의 댓글