
알고있으면 좋은 Javascript Tip✨
toFixed()
- toFixed() 메서드는 매개변수로 소수점 자리수를 채워주면 그 자리수 만큼 반올림하여 문자열로 리턴해주는 소수점 처리 메서드이다.
(1) toFixed 기본 문법
- toFixed 메서드는 Number 인스턴스의 소수 부분 자릿수를 전달받은 값으로 고정한 후, 그 값을 문자열로 반환한다.
numObj.toFixed([소수 부분의 자릿수])
- 매개변수 : 소수점 뒤에 나타날 자릿수
- 0 이상 100 이하의 값이 사용 가능하고, 값을 지정하지 않으면 0을 사용한다.
- 반환 값(return) : 숫자를 고정 소수점 표기법으로 표기해 반환
- 소수점 이하가 길면 숫자를 반올림하고, 짧아서 부족할 경우 뒤를 0으로 채운다.
(2) toFixed 동작 과정
let numObj = 1.23456
console.log(numObj.toFixed()); // 결과값: '1'
console.log(numObj.toFixed(6)); // 결과값: '1.234560'
console.log(numObj.toFixed(3)); // 결과값: '1.235'
console.log(numObj.toFixed(1)); // 결과값: '1.2'
(3) toFixed 예제 활용
const sampleData = {
now: 4.23,
max: 6.01
}
function setInSideWaterLevel(now: number, max: number) {
const isNow: HTMLSpanElement | null = document.querySelector("");
const isMax: HTMLSpanElement | null = document.querySelector("");
if (isNow && isMax) {
isNow.innerText = now.toFixed(1);
isMax.innerText = max.toFixed(1);
}
console.log(isNow) // 결과값: 4.2
console.log(isMax) // 결과값: 6.0
}
setInSideWaterLevel(sampleData.now, sampleData.max;'Study > JavaScript' 카테고리의 다른 글
| [JS] Class (0) | 2023.10.26 |
|---|---|
| [JS] getBoundingClientRect (0) | 2023.10.19 |
| [JS] padStart & padEnd (0) | 2023.10.17 |
| [JS] reduce (0) | 2023.10.17 |
| [JS] call & apply & bind (0) | 2023.10.05 |