본문 바로가기
Front-End/javascript

[Javascript 기초] 숫자 관련 객체 Math

by 김기. 2023. 5. 31.

숫자 관련 객체

1. Math.round()

2. Math.pow()

3. Math.sqrt()

4. Math.abs()

5. Math.ceil()

6. Math.floor()

7. Math.min()

8. Math.max()

9. Math.random()


1. Math.round()

Math.round(x)는 입력값 x에서 제일 근접한 정수를 반환합니다. (반올림, 반내림)

console.log(Math.round(4.3)); // 4

 

2. Math.pow()

Math.pow(x, y)는 x에 y를 제곱한 값을 반환합니다.

console.log(Math.pow(2, 4)); // 16

 

3. Math.sqrt()

Math.sqrt(x)는 x의 제곱근을 반환합니다.

console.log(Math.sqrt(25)); // 5

 

4. Math.abs()

Math.abs(x)는 x의 양수 값을 반환합니다.

console.log(Math.abs(-8.6)); // 8.6

 

5. Math.ceil()

Math.ceil(x)은 x값에서 소수점 아래 값을 올림한 정수로 반환합니다.

console.log(Math.ceil(2.004)); // 3
console.log(Math.ceil(-2.004)); // -2

 

6. Math.floor()

Math.floor(x)는 x값에서 소수점 아래 값을 버린 정수로 반환합니다.

console.log(Math.floor(7.9972)); // 7
console.log(Math.floor(-7.9972)); // -8

 

7. Math.min()

Math.min()은 인수로 넣은 값들 중 제일 작은 값을 반환합니다.

console.log(Math.min(1, 2, 3, 4, 5)); // 1
console.log(Math.min(-1, -2, -3, -4, -5)); // -5

 

8. Math.max()

Math.max()는 인수로 넣은 값들 중 제일 큰 값을 반환합니다.

console.log(Math.max(1, 2, 3, 4, 5)); // 5
console.log(Math.max(-1, -2, -3, -4, -5)); // -1

 

9. Math.random()

Math.random()은 0에서 1사이의 실수를 랜덤으로 반환합니다.

console.log(Math.random()); // 0 ~ 1 실수, ex) 0.048512159507417385

만약 특정수까지 랜덤한 정수를 반환하고자 한다면 Math.floor()를 사용할 수 있습니다.

console.log(Math.floor(Math.random() * 10) + 1); // 1 ~ 10 정수, ex) 10

댓글