[JS] 숫자, 수학 method

nana·2023년 1월 13일
0

🟡 JavaScript

목록 보기
18/23
post-thumbnail

🖍️ Number

toString( ) : 숫자를 문자로 변경

// 10진수 → 2진수 / 16진수
let num = 10;
num.toString();     // "10"
num.toString(2);    // "1010"

let num2 = 255;
num2.toString(16);  // "ff"

🖍️ Math

💟 Math.ceil( ) : 올림

let num1 = 5.1;
let num2 = 5.7;

Math.ceil(num1);  // 6
Math.ceil(num2);  // 6

💟 Math.floor( ) : 내림

let num1 = 5.1;
let num2 = 5.7;

Math.floor(num1);  // 5
Math.floor(num2);  // 5

💟 Math.round( ) : 반올림

let num1 = 5.1;
let num2 = 5.7;

Math.round(num1);  // 5
Math.round(num2);  // 6

💟 toFixed( ) : 소수점 자릿수

  • 숫자를 인수로 받아 그 숫자만큼 소수점 이하 갯수를 반영
  • 통계, 지표 작업 시 많이 사용됨
  • 단, 문자열을 반환하니 주의 ❗️
    반환받은 이후 Number를 이용해 숫자로 변환 후 작업하는 경우가 많음
// 요구사항 : 소수점 둘째자리 까지 표현 (셋째 자리에서 반올림)

let userRate = 30.1234;

userRate * 100  // 3012.34
Math.floor(userRate * 100)  // 3012
Math.floor(userRate * 100) / 100  // 30.12

→ 📍 toFixed() 사용

let userRate = 30.1234;
userRate.toFixed(2);  // "30.12"

userRate.toFixed(0);  // "30"
userRate.toFixed(6);  // "30.123400"

→ 📍 Number() 사용

let userRate = 30.1234;
Number(userRate.toFixed(2));  // 30.12

💟 isNaN( )

  • NaN 인지 아닌지를 판단할 수 있는 것은 isNaN 만 가능
let x = Number ('x'); // NaN

x == NaN   // false
x === NaN  // false
x == NaN   // false

→ 📍 isNaN 사용

isNaN(x)   // true
isNaN(3)   // false

💟 parseInt( )

  • 문자열을 숫자로 바꿔줌
  • 문자가 혼용되어 있어도 작동
  • 정수만 반환
let margin = '10px';
parseInt(margin);  // 10
Number(margin);    // NaN

let redColor = 'f3';
parseInt(redColor);  // NaN

let redColor = 'f3';
parseInt(redColor, 16);  // 243

💟 parseFloat( )

  • parseInt와 동일하게 동작하지만 부동 소수점을 반환
let padding = '18.5%';
parseInt(padding);    // 18
parseFloat(padding);  // 18.5

💟 Math.random( ) : 0 ~1 사이 무작위 숫자 생성

// 1 ~ 100 사이 임의의 숫자를 뽑고 싶다면? 

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

💡 실행 시킬때 마다 다른 값 나옴
❓ 마지막에 +1을 하는 이유
→ random 값이 내림 후 0이 될 수 있기 때문에 최소값 1을 더해줌

💟 Math.max( ) / Math.min( )

  • 괄호 안 인수들 중 최대 / 최소 값 구할 수 있음
Math.max(1, 4, -1, 5, 10, 9, 5.54);  // 10
Math.min(1, 4, -1, 5, 10, 9, 5.54);  // -1

💟 Math.abs( ) : 절대값

  • abs는 absolute의 약어
Math.abs(-1);  // 1

💟 Math.pow(n, m) : 제곱

  • pow는 power의 약어
Math.pow(2, 10);  // 1024 (2의 10승)

💟 Math.sqrt( ) : 제곱근

  • sqrt는 square root의 약어
Math.sqrt(16);  // 4 (루트 16)
profile
✧ 중요한건 꺾이지 않는 마음 🔥 ᕙ(•ө•)ᕤ 🔥

0개의 댓글