수학 계산을 위해서는 JavaScript에서 제공하는 Math 객체를 사용한다.
Math.log () 메서드로 이동하여 참고해보자.
그 중, 자주 사용하는 3가지에 대하여 정리해보면,
Math.round
함수를 사용하여 반올림을 사용해야 하는 경우 예시 평균 값을 구한 후 별점을 칠할 때 등이 있다.
console.log(Math.round(2.5));
console.log(Math.round(2.49));
console.log(Math.round(2));
console.log(Math.round(2.82));
console.log(Math.ceil(2.5));
console.log(Math.ceil(2.49));
console.log(Math.ceil(2));
console.log(Math.ceil(2.82));
console.log(Math.floor(2.5));
console.log(Math.floor(2.49));
console.log(Math.floor(2));
console.log(Math.floor(2.82));
let randomNumber = Math.random();
console.log(randomNumber);
0.0000000000000000에서 0.9999999999999999 사이의 값에서 랜덤수를 제공하지만, 아래와 같이 랜덤함수를 이용해서 개발자가 원하는 범위의 랜덤수를 설정할 수 있다.
var randomNumber = Math.random();
console.log(Math.floor(randomNumber*10));
이렇게 구한 소수자리는 내림함수를 사용하여 0~10 사이의 랜덤수를 구할 수 있다.
- 최소(min), 최대값(max)을 받아 그 사이의 랜덤수를 return 하는 함수를 구현
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
- 두 값 사이의 정수 난수 생성하기
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //최댓값은 제외, 최솟값은 포함
}
- 최댓값을 포함하는 정수 난수 생성하기
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //최댓값도 포함, 최솟값도 포함
}
조건에 따른 식 자체를 도출해내기 이렵다고 생각할때.. MDN을 만났다 😇 참고