Dev./jQuery
[Javascript] 소수점 처리방법 두번째
Alx.K
2023. 1. 31. 23:05
반응형
오늘은 javascript 에서 소수점을 처리하는 두가지 방법 toPrecision 과 toFixed 메서드 중에서 수의 길이를 제한할 수 있는 toPrecision 에 대해 정리합니다.
toPrecision
Number 인스턴스의 ㄱ가수와 소수 부부을 합친 자릿수를 전달받은 값으로 고정한 후, 문자열로 반환합니다.
numObj.toPrecision([전체자릿수])
매개변수
유효 자릿수를 지정하는 정수로 생략이 가능합니다.
반환 값 (Return)
고정 소수점 또는 지수 표기법의 수를 정밀 유효 숫자로 반올림 한 문자열을 반환합니다.
인수가 생략된 경우 Number.prototype.toString()처럼 동작하며 인수가 정수가 아닌 값이면 갖아 가까운 정수로 반올림합니다.
사용예제
let numObj = 1.23456
console.log(numObj.toPrecision()); // 결과 : '1.23456'
console.log(numObj.toPrecision(5)); // 결과 : '1.2346'
console.log(numObj.toPrecision(3)); // 결과 : '1.23'
console.log(numObj.toPrecision(1)); // 결과 : '1'
numObj = 0.0005678
console.log(numObj.toPrecision()); // 결과 : '0.0005678'
console.log(numObj.toPrecision(5)); // 결과 : '0.00056780'
console.log(numObj.toPrecision(3)); // 결과 : '0.000568'
console.log(numObj.toPrecision(1)); // 결과 : '0.0006'
numObj = 12345.67
console.log(numObj.toPrecision(2)); // 결과 : '1.2e+4'
※ 주의 사항
인수가 1에서 100 사이가 아닌 경우 RangeError 가 발생합니다.
ECMA-262는 최대 21개의 유효 자릿수의 정밀도를 필요로 합니다.
반응형