1. 제곱근
- Math.sqrt(25) // 5
2. 최댓값
- Math.max(5, 18, 23, 11) // 23
3. 최솟값
- Math.min(5, 18, 23, 11) // 5
4. 원주율
- Math.PI // 3.141592......
5. 난수
- Math.random() // 0-1 사이 난수 생성
ex) 0 - 5 사이 난수 생성
- Math.trunc(Math.random() * 6)
cf) Math.trunc는 소수점 이하 숫자 무시, 오직 정수부만 return
ex2) 특정 수 사이 난수 생성
- const randomNum = (min, max) => Math.trunc(Math.random() * (max - min) + 1) + min
6. 소수점 처리
- Math.trunc(23.3) // 23 - 제거
- Math.floor(23.3) // 23 - 버림
- Math.round(23.9) // 23 - 반올림
- Math.ceil(23.4) // 24 - 올림
cf1> 위 4개의 메소드는 형변환이 이루어짐
- Math.floor('23.3') - 23(int)
cf2 > Math.trunc vs Math.floor
- 인자가 양수인 경우 두 함수는 같은 결과를 return 하지만,
음수인 경우 trunc는 양수와 마찬가지로 정수부만 return하지만,
floor는 양수와 달리 정수 - 1을 return
- ex) Math.trunc(-23.3) // -23
Math.floor(-23.3) // -24
7. toFixed
(2.7).toFixed(0) // "3"
- 항상 string을 return
- toFixed 내부 인자의 수만큼 소수점 뒤에 0을 붙임
- ex)(2.7).toFixed(3) // "2.700" - 소수점 다음 자릿수가 3개
- 만약 인자로 들어온 수와 소수점 뒤의 자릿수가 더 크다면 반올림
- ex) (2.345).toFixed(2) // 2.35 - 소수점 둘째 자리까지 반올림
- ex) (2.8).toFixed(1) // 2.8 - 같다면 유지
'TIL > JavaScript' 카테고리의 다른 글
| Date object & method (0) | 2022.12.16 |
|---|---|
| Numeric Separator & bigInt (0) | 2022.12.16 |
| Converting and Checking numbers (0) | 2022.12.16 |
| Closure (0) | 2022.10.05 |
| Call, Apply, Bind (0) | 2022.09.27 |