■ Front-End ■/JavaScript

[JavaScript] 학습정리 - 9.Number 객체

한길(One Way) 2023. 3. 1.

자바스크립트는 객체 기반 함수형 스크립트 언어이며 웹에서 중요한 위치를 차지하고 있다.

 

이번에는 Number 객체에 대하여 알아보자. Number 객체에서 사용하는 메서드에는 주로 값에 대한 변환하는 기능을 갖고 있다.

  • toExponential: 소수점 이하의 숫자 개수로 지수표현
  • toPrecision: 표현하는 유효숫자
  • toFixed: 소수점 이하 자릿수만 남기고 반올림하여 표시 
var value = new Number(123.456789);
value.toExponential(3) // 1.235e+2
value.toPrecision(4) // 123.5
value.toFixed(3) // 123.457



number.toExponential(fractionDigits)
toExponential 메소드는 숫자를 지수 형태의 문자열로 변환합니다.

console.log(Math.PI.toExponential(0)); // 3e+0
console.log(Math.PI.toExponential(2)); // 3.14e+0 
console.log(Math.PI.toExponential(7)); // 3.1415927e+0 
console.log(Math.PI.toExponential(16)); // 3.1415926535897931e+0
console.log(Math.PI.toExponential( )); // 3.141592653589793e+0


number.toFixed(fractionDigits)
toFixed 메소드는 숫자를 고정 소수점 형태로 변환합니다.

console.log(Math.PI.toFixed(0)); // 3
console.log(Math.PI.toFixed(2)); // 3.14
console.log(Math.PI.toFixed(7)); // 3.1415927
console.log(Math.PI.toFixed(10)); // 3.1415926536
console.log(Math.PI.toFixed( )); // 3


number.toPrecision(precision)
toPrecision 메서드는 숫자를 10진수 형태의 문자열로 변환합니다.

console.log(Math.PI.toPrecision(2)); // 3.1
console.log(Math.PI.toPrecision(7)); // 3.141593
console.log(Math.PI.toPrecision(10)); // 3.141592654
console.log(Math.PI.toPrecision( )); // 3.141592653589793


number.toString(radix)
toString 메소드는 숫자를 문자열로 변환합니다.
radix 매겨변수는 진법을 지정합니다. 기본값은 10입니다.

console.log(Math.PI.toString(2)); // 11.001001000011111101101010100010001000010110100011
console.log(Math.PI.toString(8)); // 3.1103755242102643
console.log(Math.PI.toString(16)); // 3.243f6a8885a3
console.log(Math.PI.toString( )); // 3.141592653589793




728x90

댓글