Math()

프최's log·2020년 8월 26일
0

Javascript

목록 보기
15/26

참조사이트 - Math : MDN
★ 본문 내용 중 위와 같은 색상으로 된 글자는 해당하는 MDN 페이지가 연결되어있습니다.

1.Math

  • 수학적 상수&함수를 위한 속성과 메소드를 가진 내장 객체(함수 객체는 아님)
  • Number 자료형만 지원

2.정적 속성(Static properties)

  • 친근하게 많이 봤던 값 위주의 속성만 적어두었습니다.
    더 많은 속성은 MDN 참조!
정적속성이름
Math.E오일러의 상수이며 자연로그의 밑, 약 2.718
Math.PI원의 둘레와 지름의 비율, 약 3.14159
Math.SQRT1_21/2의 제곱근, 약 0.707
Math.SQRT22의 제곱근. 약 1.414

3.정적 메소드

  • 사용해봤던 메소드만 정리 해두었습니다.
    더 많은 메소드는 [MDN 참조]

1) 절대값 : Math.abs()

  • Math.abs(args)
  • 인자(args)에 대한 절대값을 반환한다.
  • 절대값? 실수에서 부호를 제거한 값
    • 3의 절대값은 -3/3 이다.

2) 최대값 & 최소값 : Math.max() & Math.min()

  • Math.max(value)
    • 주어진 숫자 중 가장 큰 값(max)을 반환한다.
  • Math.min(value)
    • 주어진 숫자 중 가장 작은 값(min)을 반환한다.

3) Math.random

  • Math.random()
  • 0과 1사이의 랜덤한 수를 리턴
  • 범위를 설정해주고 싶을 경우, random() 뒤에 * 최대 범위를 설정해주시면 된다.
let a = function (){
  return Math.random()*100
};

a();
> 33.71958943641307
a();
> 27.990881438932224

//올림을 통한 정수 반환
let a = function (){
return Math.ceil(Math.random()*100)
};

a();
>7
a();
>48

4) Math.sqrt

  • Math.sqrt(value)
  • value의 제곱근(square root of the given number)을 리턴한다.
  • 음수일 경우, NaN을 리턴한다.

5) Math.pow

  • Math.pow(base, exponent)
  • base는 '밑'에 해당하며 exponent는 '지수'에 해당한다.

6) 반올림/올림/내림 : Math.round / Math.ceil / Math.floor

  • Math.round(value)
    • 소수점에 가까운 정수로 반올림한 값
  • Math.ceil(value)
    • 소수점에 가까운 정수를 올림한 값
  • Math.floor(value)
    • 소수점에 가까운 정수를 내림한 값

소수점 자릿수 조정은 Math 메소드에 없는걸까?
Math 객체가 아닌 Number 객체의 메소드에서 관리된다.

7) 소수점 자릿수 조정 : toFixed

  • value.toFiexd(x)
  • value에는 변수나 number를 적어주고, x 안에 원하는 자릿수를 적어주면 x만큼의 수만 표기된다.
let value = 12.34567;

value.toFixed();
> "12"
value.toFixed(1);
> "12.3"
value.toFixed(2);
> "12.35"
value.toFixed(3);
> "12.346"
value.toFixed(10); // 추가 요청한 자릿수는 0으로 반환
> "12.3456700000"

// 음수일 경우
-12.34.toFixed();//문자열이 아닌 수로 리턴(연산자 우선적용)
> -12

// 문자열로 리턴하고 싶다면, 변수로 설정하거나
let negativeV = -12.34

negativeV.toFixed()
>"-12"

// 소괄호를 쳐준다.
(-12.34).toFixed()
> "-12"

그외 참조 : 코드스테이츠

profile
차곡차곡 쌓아가는 나의 개발 기록

1개의 댓글

comment-user-thumbnail
2022년 6월 15일

Whether you're looking for a new game to keep your little one entertained or simply want to reinforce a concept at home, kids math games https://kids-math-games.com/measurement-games/ can help. Here are some games to try. These will give your child a fun way to practice math and encourage logical thinking. In addition to these games, here are some of my favorites for preschoolers. You can find more kids math games on my website or on Amazon. If you're looking for an educational game to play with your children, I highly recommend trying Snap It Up!

답글 달기