본문 바로가기

js

[javascript] 난수 생성하는 방법 (Math.random)

1. Math.random()

 

0보다 크고 1보다 작은 난수를 생성함

const random = Math.random();
// 0.6364770534432618

 

 

2. 정수 난수 만들기

 

Math.floor()를 사용하여 정수로 만들 수 있음

 

Math.round : 반올림

Math.ceil : 올림

Math.floor : 내림

 

Math.floor(Math.random() * 10); 는 0~9까지의 정수를 반환

10을 포함하고 싶다면 Math.floor(Math.random() * 11); 로 사용하면 된다.

Math.floor(Math.random() * 100); 는 0~99까지의 정수를 반환

(Math.random()의 결과값이 0~0.99999... 이기 때문)

const random = Math.floor(Math.random() * 10);
// 7