자바스크립트에서 Math 객체를 사용하면 숫자에 대한 수학적 작업을 할 수 있다. Math는 생성자가 아닌 객체이다. 그래서 new 연산자를 통하여 객체를 생성하는 것이 아닌, Math 자체가 객체이므로 바로 사용하면 된다.
Math 객체의 상수
상수 | 예시 |
E | 오일러의 상수(약 2.718) |
LN2 | 밑수가 2인 자연로그 (약 0.693) |
LN10 | 밑수가 10인 자연로그 (약 2.302) |
PI | PI 값 (약 3.14) |
SQRT1_2 | 1/2의 제곱근 (약 0.707) |
SQRT2 | 2의 제곱근 (약 1.414) |
Math 객체의 메서드
메서드 | 설명 |
abs(x) | x의 절대값 |
acos(x), asin(x), atan(x) | x(라디안)의 아크 삼각함수 |
ceil(x) | 실수를 정수로 (올림) |
cos(x), sin(x), tan(x) | x(라디안)의 삼각함수 |
exp(x) | 지수 함수 |
floor(x) | 실수를 정수로 (버림) |
log(x) | 로그 함수 |
max(x,y,z...,n) | 최대값 |
min(x,y,z,...,n) | 최소값 |
pow(x,y) | 지수 함수 x의 y승 |
random() | 0과 1 사이의 난수 값 |
round(x) | 반올림한 정수 |
sqrt(x) | x의 제곱근 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let a = Math.round(4.7);
let b = Math.round(4.4);
let c = Math.pow(8,2);
let d = Math.sqrt(65);
let e = Math.abs(-4.7);
let f = Math.ceil(4.7);
let g = Math.floor(4.7);
let h = Math.sin(90*Math.PI/180);
let i = Math.cos(0*Math.PI/180);
let j = Math.max(3, 124, 32, -8, 99, -17);
let k = Math.min(3, 124, 32, -8, 99, -17);
let l = Math.random();
document.write("<b>Math.round(4.7) : </b>" + a + "<br>");
document.write(`<b>Math.round(4.4) : </b> ${b} <br>`)
document.write(`<b>Math.pow(8,2) : </b> ${c} <br>`)
document.write(`<b>Math.sqrt(65) : </b> ${d} <br>`)
document.write(`<b>Math.abs(-4.7) : </b> ${e} <br>`)
document.write(`<b>Math.ceil(4.7) : </b> ${f} <br>`)
document.write(`<b>Math.floor(4.7) : </b> ${g} <br>`)
document.write(`<b>Math.sin(90*Math.PI/180) : </b> ${h} <br>`)
document.write(`<b>Math.cos(0*Math.PI/180) : </b> ${i} <br>`)
document.write(`<b>Math.max(3, 124, 32, -8, 99, -17) : </b> ${j} <br>`)
document.write(`<b>Math.min(3, 124, 32, -8, 99, -17) : </b> ${k} <br>`)
document.write(`<b>Math.random() : </b> ${l} <br>`)
</script>
</body>
</html>
'웹 프로그래밍 기초 > 객체' 카테고리의 다른 글
내장 객체 (RegExp) (1) | 2025.04.09 |
---|---|
내장 객체 (Number) (0) | 2025.04.09 |
get메서드 / set메서드 (0) | 2025.04.09 |
내장 객체 (Date) (0) | 2025.04.09 |
repeat() (0) | 2025.04.09 |