[JS] Math 메서드

KJA·2023년 2월 7일
0

Math.floor()

소수점 이하를 내림합니다.

console.log(Math.floor(5.95));
// Expected output: 5

console.log(Math.floor(5.05));
// Expected output: 5

console.log(Math.floor(5));
// Expected output: 5

console.log(Math.floor(-5.05));
// Expected output: -6

Math.ceil()

소수점 이하를 올림합니다.

console.log(Math.ceil(.95));
// Expected output: 1

console.log(Math.ceil(4));
// Expected output: 4

console.log(Math.ceil(7.004));
// Expected output: 8

console.log(Math.ceil(-7.004));
// Expected output: -7

Math.round()

소수점 이하를 반올림합니다.

console.log(Math.round(0.9));
// Expected output: 1

console.log(Math.round(5.95), Math.round(5.5), Math.round(5.05));
// Expected output: 6 6 5

console.log(Math.round(-5.05), Math.round(-5.5), Math.round(-5.95));
// Expected output: -5 -5 -6

Math.trunc()

소수부분을 제거하고 숫자의 정수부분을 반환합니다.

console.log(Math.trunc(13.37));
// Expected output: 13

console.log(Math.trunc(42.84));
// Expected output: 42

console.log(Math.trunc(0.123));
// Expected output: 0

console.log(Math.trunc(-0.123));
// Expected output: -0

Math.random()

이 함수는 0~1(1은 미포함) 구간에서 부동소수점의 난수를 생성합니다.

범위를 지정한 난수 생성

Math.floor(Math.random() * 100); // 0 ~ 99

Math.floor(Math.random() * 101); // 0 ~ 100

Math.floor(Math.random() * 100) + 1 // 1 ~ 100

두 값 사이의 난수 생성하기

이 예제는 주어진 두 값 사이의 난수를 생성합니다. 함수의 반환값은 min보다 크거나 같으며, max보다 작습니다.

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

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

이 예제는 주어진 두 값 사이의 정수인 난수를 생성합니다. 반환값은 min(단, min이 정수가 아니면 min보다 큰 최소의 정수)보다 크거나 같으며, max보다 작습니다.

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

최댓값을 포함하는 정수 난수 생성하기

위의getRandomInt() 함수는 최솟값을 포함하지만, 최댓값은 포함하지 않습니다. 최솟값과 최댓값을 모두 포함하는 결과가 필요할 경우, 아래의 getRandomIntInclusive() 함수를 사용할 수 있습니다.

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

0개의 댓글