Notice
Recent Posts
Recent Comments
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

HYEWON JUNG의 개발일지

Math 메소드 살펴보기!Math.abs() Math.ceil() Math.floor() Math.round()Math.trunc()Math.max()Math.min()Math.pow()Math.sign() Math.sign() 본문

JavaScript

Math 메소드 살펴보기!Math.abs() Math.ceil() Math.floor() Math.round()Math.trunc()Math.max()Math.min()Math.pow()Math.sign() Math.sign()

혜won 2023. 11. 26. 17:11

Math.abs() 절대값 반환

리턴값이 0또는 양수면 그대로

리턴값이 음수면 반대값인 양수로 반환한다.

function mathAbs(a, b) {
  return Math.abs(a - b);
}

function origin(a, b) {
  return a - b;
}

console.log("Abs=>", mathAbs(2, 5)); //3  원래 -3이지만 3으로 반환
console.log("origin=>", origin(2, 5)); //-3
console.log("Abs2=>", mathAbs(5, 2)); //3
console.log("origin2=>", origin(5, 2)); //3  3 그래도 반환

function one(x) {
  return Math.abs(x);
}

console.log("x=>", one(3));  //3
console.log("-x=>", one(-3));  //3

Math.ceil() 올림

function mathCeil(a, b) {
  return Math.ceil(a / b);
}
console.log("M=>", mathCeil(5.36, 3)); //2

function origin(a, b) {
  return a / b;
}
console.log("O=>", origin(5.36, 3)); //1.7866666666666668

Math.floor() 내림

console.log("Math", Math.floor(5.984 * 33)); //197
console.log("Ori", 5.984 * 33); //197.472

Math.round() 반올림

console.log(Math.round(0.9)) //1

Math.trunc() 소수 자르기

console.log(Math.trunc(13.37));//  13
console.log(Math.trunc(42.84));//  42

Math.max() 가장 큰 숫자 반환

const testArray = [4, 9, 2 / 4, 12, 2 ** 5];

console.log(Math.max(...testArray)); //2**5 인 32
console.log(Math.max(5, 4, 8, 26));  //26

Math.min() 가장 작은 숫자 반환

* 모든 인자가 숫자형으로 변환이 가능해야함 아닐경우 NaN 반환

* 인자가 없으면 infinity반환

const testArray = [4, 9, 2 / 4, 12, 2 ** 5];

console.log(Math.min(...testArray));

Math.pow() 제곱(?)

기본형 

console.log(Math.pow(base, exponent)); math

 

예제

console.log(Math.pow(5, 2)); //25
console.log(Math.pow(3, -2)); //0.11111111111111

Math.sqrt() 제곱근

console.log(Math.sqrt(121))//11

Math.sign() 부호에 따라 반환

양수의 경우 1 을 음수 일 땐 -1 0일경우 부호에 따라 -0, 0 나뉨

인자의 데이터 타입이 숫자형이 아니여도 자동으로 형변환을 한다.

console.log(Math.sign(3)); //1
console.log(Math.sign(-3)); // -1
console.log(Math.sign(0)); // 0
console.log(Math.sign(-0)); // -0
//자동으로 숫자형으로 변형
console.log(Math.sign("-3")); // -1 
console.log(Math.sign(true)); // 1
console.log(Math.sign(false)); //0

console.log(Number(true)); //1
console.log(Number(false)); //0

 

 

Mdn 문서 참고

'JavaScript' 카테고리의 다른 글

콜백함수 (제어권, this binding)  (0) 2023.10.30
실행컨텍스트(VE, LE, record, hoisting 등)  (0) 2023.10.30
데이터 타입 > 얕은 복사 , 깊은 복사  (0) 2023.10.27
Map();  (1) 2023.10.26
일급 객체로서의 함수  (0) 2023.10.26