수학과 함수를 위한 프로퍼티와 메서드를 제공하는 내장 객체.
.abs() : 절대값으로 반환. 0 혹은 양수
console.log(Math.PI); // 3.141592653589793
// .abs()
let abs = Math.abs(4); // 4
abs = Math.abs(3.141592653589793); // 3.141592653589793
abs = Math.abs(-3.141592653589793); // 3.141592653589793
abs = Math.abs("-1"); // 1 -> 숫자형 문자열도 양수로 반환
abs = Math.abs(""); // 0
abs = Math.abs(null); // 0
abs = Math.abs(undefined); // NaN
abs = Math.abs(); // NaN
abs = Math.abs('string'); // NaN
abs = Math.abs(true); // 1
abs = Math.abs(false); // 0
console.log(`abs : ${abs}`);
.round() : 소수점 이하 반올림하여 정수로 반환
let round = Math.round(31.141592653589793); // 31
round = Math.round(31.545); // 32
round = Math.round(-31.545); // -32
round = Math.round("31.499"); // 31
console.log(`round : ${round}`);
.ceil() : 소수점 이하 올림하여 정수로 반환
let ceil = Math.ceil(1.2); // 2
ceil = Math.ceil(-1.2); // -1
console.log(`ceil : ${ceil}`);
.floor() : 소수점 이하 내림하여 정수로 반환
let floor = Math.floor(1.8); // 1
floor = Math.floor(-1.8); // -2
console.log(`floor : ${floor}`);
.trunc() : 절삭. 소수점이하 삭제하고 정수로 반환
let trunc = Math.trunc(3.141592653589793); // 3
trunc = Math.trunc(1.9); // 1
trunc = Math.trunc(-1.9); // -1
trunc = Math.trunc(-9.1); // -9
console.log(`trunc : ${trunc}`);
.sqrt() : 제곱근
console.log(`sqrt : ${Math.sqrt(9)}`); // 3
.random() : 0~1사이의 랜덤 실수 반환. 0은 포함되나 1은 포함되지 않음.
console.log(`random : ${Math.random()}`); // 0.xxxxxxxxxxxxxxxx 랜덤 출력
// 1~100까지의 랜덤 정수 반환
let ran = Math.random() * 100;
console.log(Math.trunc(ran)); // 소수점 떼고 정수 반환
.min() : 제일 작은 값 반환
console.log(Math.min(0.5, 5, 10, 20)); // 0.5
.max() : 제일 큰 값 반환
console.log(Math.max(0.5, 5, 10, 20)); // 20
.toFixed() : 소수점 이하 몇자리까지만 출력
let random = Math.random();
ran = random * 10 + 1; // 1~10까지 무작위 수
console.log(ran.toFixed(3)); // 1.234 소수점 3자리가지만 출력
isNaN() : NaN이면 true, 아니면 false 반환
let str = '13'; // 숫자형 문자열
console.log(typeof str); // string
console.log(isNaN(str)); // NaN이 아니다 === false === Number
//숫자형 문자열은 숫자로 인식
console.log(isNaN('NaN이 맞으면 true')); // true
console.log(isNaN('숫자가 아니면 true')); // true
'JavaScript' 카테고리의 다른 글
| [JavaScript] 배열 (array) (0) | 2022.12.06 |
|---|---|
| [JavaScript] 구조 분해 할당 (0) | 2022.12.06 |
| [JavaScript] Date 객체와 날짜 (0) | 2022.12.05 |
| [JavaScript] String 메서드 (0) | 2022.12.05 |
| [JavaScript] JSON (0) | 2022.12.05 |