toFixed() 메서드
- 숫자를 고정 소수점 표기법(fixed-point-notation)으로 표시
- Number 인스턴스의 소수 부분 자릿수를 전달받은 값으로 고정한 후, 그 값을 문자열로 반환
function financial(x) {
return Number.parseFloat(x).toFixed(2);
}
console.log(financial(123.456));
// Expected output: "123.46"
console.log(financial(0.004));
// Expected output: "0.00"
console.log(financial('1.23e+5'));
// Expected output: "123000.00"
구문
numObj.toFixed([소수 부분의 자릿수])
매개변수
- 소수점 뒤에 나타날 자릿수
- 0~20까지의 정수
- 구현체에 따라 더 넓은 범위의 값을 지원할 수 있음
- 값을 지정하지 않으면 0을 사용
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'
'JS' 카테고리의 다른 글
[Javascript] for, foreach (0) | 2024.02.02 |
---|---|
[JS] 배열의 순서 (sort()메서드, reverse() 메서드) (0) | 2023.02.03 |
[JS]BigInt (0) | 2023.01.31 |
[JS] == , === 차이점 (0) | 2023.01.18 |
[JS] 배열 특정 값 포함 여부(includes, indexOf, some, every) (0) | 2023.01.17 |