-
JS Math자바스크립트/모듈 & 내장함수 2023. 8. 12. 22:25
주요 메서드:
- Math.abs(x): 절댓값
- Math.ceil(x): 올림
- Math.floor(x): 내림
- Math.round(x): 반올림
- Math.max(...values): 최대값
- Math.min(...values): 최소값
- Math.random(): 0 이상 1 미만의 난수
- Math.sqrt(x): 제곱근
- Math.pow(x, y): x의 y 거듭제곱 값
- Math.sin(x), Math.cos(x), Math.tan(x): 주어진 각도의 사인, 코사인, 탄젠트 값을 계산합니다.
주요 상수:
- Math.PI: 원주율(π)의 근사값인 3.141592653589793입니다.
- Math.E: 자연 상수(e)의 근사값인 2.718281828459045입니다.
- Math.LN2: 2의 자연 로그 값인 0.6931471805599453입니다.
- Math.LN10: 10의 자연 로그 값인 2.302585092994046입니다.
- Math.LOG2E: 자연 상수 e의 2의 로그 값인 1.4426950408889634입니다.
- Math.LOG10E: 자연 상수 e의 10의 로그 값인 0.4342944819032518입니다.
function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // 1부터 100 사이의 랜덤한 정수 생성 const randomValue = getRandomInt(1, 100); console.log(randomValue);
난수 예제
const number = 2.71828; const rounded = Math.round(number * 100) / 100; const fixedDecimal = number.toFixed(2); console.log(rounded); console.log(fixedDecimal); // 출력: "2.72"
반올림은 round나 toFixed를 쓸 수 있다.
toFixed는 문자열로 바뀌니 주의.
'자바스크립트 > 모듈 & 내장함수' 카테고리의 다른 글
Spawn을 활용한 배치 스크립트 (자동 실행) (0) 2023.11.07 NET 모듈로 서버 & 클라이언트 만들기 (0) 2023.08.08 crypto 모듈 - 암복호화, MAC, 난수, 서명 (0) 2023.08.06 crypto 모듈 - 해싱 (0) 2023.08.06 setTimeout(), setInterval() (0) 2023.08.05