웹개발/자바스크립트

[Js] Math.random() - 랜덤숫자(난수)생성하기

webvillain 2021. 8. 8. 02:53

Math.random() 

 

Math.random() 함수는 0 이상 1 미만의 부동소숫점 의사 난수를 반환하며, 이 값은 사용자가 원하는 범위로 변형할 수 있다.

 

 

1. 0 이상 1 미만의 난수 생성하기

function getRandom() {
  return Math.random();
}

See the Pen Math.random() - 난수생성 by mk (@kmeijing) on CodePen.

 

 

2. 두 값 사이의 난수 생성하기

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

See the Pen Math.random() - 두값사이의 난수 생성 by mk (@kmeijing) on CodePen.

 

 

3. 두 값 사이의 정수 난수 생성하기

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //최댓값은 제외, 최솟값은 포함
}

See the Pen by mk (@kmeijing) on CodePen.

 

 

4. 최대값을 포함하는 정수 난수 생성하기

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //최댓값도 포함, 최솟값도 포함
}

See the Pen Math.random() - 최댓값 포함하는 정수 난수 생성 by mk (@kmeijing) on CodePen.