kimmgamjja

[JavaScript] 소수점 처리 toFixed() 본문

공부/JavaScript

[JavaScript] 소수점 처리 toFixed()

인절미댕댕이 2025. 1. 24. 08:00
728x90

toFixed()

numObj.toFixed([소수 부분의 자릿수])

 

: Number 인스턴스의 소수 부분 자릿수를 전달받은 값으로 고정한 후, 그 값을 문자열로 반환

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'

numObj = 0.0005678 
console.log(numObj.toFixed()); // 결과: '0'
console.log(numObj.toFixed(5)); // 결과: '0.00057'
console.log(numObj.toFixed(3)); // 결과: '0.001'
console.log(numObj.toFixed(1)); // 결과: '0.0'

numObj = 12345.67 
console.log(numObj.toFixed(101)); // 결과: '오류'

 

- 소수점 이하가 길면 숫자를 반올림하고, 짧아서 부족할 경우 뒤를 0으로 채운다.

 

https://junghn.tistory.com/entry/JavaScript-소수점-처리-방법-toFixed-사용법과-예제

728x90