Ziks

JS Math 본문

Development/Nodejs

JS Math

YunZiks 2019. 7. 10. 20:24

Math.abs(x); // x의 절댓값 리턴

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

Math.max(x); // x 내의 최댓값 리턴

console.log(Math.max(3, -5, 4, -100, 99)); // 99

Math.min(x); // x 내의 최솟값 리턴

console.log(Math.min(3, -5, 4, -100, 99)); // -100 

Math.pow(x, y); // x**y 리턴

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

Math.sqrt(x); // x의 제곱근 리턴

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

Math.round(x.y); // x.y를 반올림하여 리턴

  • 소숫점 부분이 0.5 이상 이라면

    • 올림
  • 소숫점 부분이 0.5 미만 이라면

    • 내림

      console.log(Math.round(4.3)); // 4
      console.log(Math.round(4.4)); // 4
      console.log(Math.round(4.49)); // 4
      console.log(Math.round(4.5)); // 5

Math.floor(x); // 소숫점 버림 값 리턴

console.log(Math.floor(3.6)); // 3 
console.log(Math.floor(2.1)); // 2 

Math.ceil(x); // 소숫점 올림 값 리턴

console.log(Math.ceil(3.3)); // 4
console.log(Math.ceil(2.29)); // 3

Math.random(); // 랜덤값출력

  • 기본적으로 0이상 1이하의 값을 리턴함

  • 정숫값을 출력하고 싶을 경우Math.floor()을 이용하여

    • 0~10 까지의 랜덤값 출력console.log(Math.floor(Math.random()*10) + 1);

    • 0~1000까지의 랜덤값 출력console.log(Math.floor(Math.random()*1000) + 1);

      console.log(Math.random()); // 0이상 1이하의 값
      console.log(Math.floor(Math.random() * 10 ) + 1); // 0 ~ 10 값

참고: MDN

'Development > Nodejs' 카테고리의 다른 글

Node.js에서의 Development Mode, Production Mode 분기  (0) 2020.12.08
Comments