Math는 수학적인 상수와 함수를 위한 속성과 메서드를 가진 내장 객체. 함수 객체 X
Math.ceil()
: 올림. 주어진 숫자보다 크거나 같은 숫자 중 가장 작은 숫자를 integer
로 반환Math.round()
: 반올림. 입력값을 반올림한 수와 가장 가까운 숫자를 integer
로 반환Math.floor()
: 버림. 주어진 숫자와 같거나 작은 정수 중에서 가장 큰 숫자를 integer
로 반환let a = 123.456
console.log(a, Math.ceil(a), Math.round(a), Math.floor(a))
//result : 123.456 124 123 123
let b = 987.654
console.log(b, Math.ceil(b), Math.round(b), Math.floor(b))
//result : 987.654 988 988 987
let c = -123.456
console.log(c, Math.ceil(c), Math.round(c), Math.floor(c))
//result : -123.456 -123 -123 -124
let d = -987.654
console.log(d, Math.ceil(d), Math.round(d), Math.floor(d))
//result : -987.654 -987 -988 -988
toFixed() 메서드는 숫자를 고정 소수점 표기법으로 표기해 string
타입으로 반환합니다.
let a = 123.456
console.log(a, a.toFixed(1), a.toFixed(2)) // 소수점 한자리, 두자리로 표현
console.log(typeof(a), typeof(a.toFixed(1)), typeof(a.toFixed(2)))
//result : 123.456 123.5 123.46
//result : number string string
자릿수만큼 10을 곱하고 Math로 값을 도출한 후 다시 10으로 나눠야 합니다
// 소숫점 두번째 자리에서 올림, 반올림, 버림을 하고 싶어요!
let a = 123.456
console.log(a, Math.ceil(a*10)/10, Math.round(a*10)/10, Math.floor(a*10)/10)
// result : 123.456 123.5 123.5 123.4