반응형
이번 글은 jQuery 보다는 Javascript 에 가까운데요.
소수점을 처리하는 두가지 방법 toPrecision 과 toFiexed 메서드 중 소수점의 자릿수를 제한할 수 있는
toFixed 에 대하여 정리를 해 놓습니다.
toFixed
number 인스턴스의 소수 부분 자릿수를 전달받은 갓ㅂ으로 고정한 후, 문자열로 반환합니다.
numberObj.toFixed([소수부분자리수])
매개변수
소수점 뒤에 나타날 자릿수 입니다.
0 이상 100 이사의 값을 사용할 수 있으며, 구현체에 따라 더 넓은 범위의 값을 지원할 수도 있습니다.
default 는 0 입니다.
반환값 (return)
숫자를 고정 소수점 표기법으로 표기해 반환합니다.
소수점 이하가 길면 숫자를 반올림하고, 짧아서 부족할 경우 뒤를 0으로 채웁니다.
메서드를 호출한 숫자의 크기가 1e+21보다 크다면 Number.prototype.toString()을 호출하여 받은 주시 표기법 결과를 대신 반환합니다.
사용 예제
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.00005678
console.log(numObj.toFixed()); // 결과 : '0'
console.log(numObj.toFixed(5)); // 결과 : '0.000057'
console.log(numObj.toFixed(3)); // 결과 : '0.001'
console.log(numObj.toFixed(1)); // 결과 : '0.0'
numObj = 12345.67
console.log(numObj.toFixed(101); // 결과 : 'error'
※ 주의사항
파라미터가 0과 100사이의 값이 아니라면
Uncaught RangeError: toFixed() digits argument must be between 0 and 100라는 오류가 발생됩니다.
반응형
'Dev. > jQuery' 카테고리의 다른 글
checkbox 클릭시 이벤트 (0) | 2023.03.08 |
---|---|
[Javascript] 소수점 처리방법 두번째 (0) | 2023.01.31 |
jQuery Focus 지정 (0) | 2023.01.28 |
jQuery 키코드로 키보드 입력 확인 (2) | 2023.01.27 |
jQuery에서 checkbox 체크 혹은 체크 해제시 이벤트 발생 (0) | 2023.01.26 |