Number객체는 원시 타입 number를 다룰 때 필요한 프로퍼티와 메소드를 제공하는 래퍼(wrapper)객체이다. 변수 또는 객체의 프로퍼티가 숫자를 값으로 가지고 있다면 Number 객체의 생성없이 Number 객체의 프로퍼티와 메소드를 사용할 수 있다.
Number 객체는 생성자 함수를 통해 생성할 수 있다.
const num1 = 78;
const num2 = new Number(78); // Number 객체 생성
console.log(num1); // 78
console.log(num2); // [Number: 78]
console.log(typeof num1); // number
console.log(typeof num2); // object
정적인 프로퍼티 (static)로, Number 객체를 생성하지 않아도 Number.프로퍼티이름
의 형태로 사용할 수 있다.
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
console.log(Number.NaN); // NaN
console.log(Number.POSITIVE_INFINITY); // Infinity
console.log(Number.NEGATIVE_INFINITY); // -Infinity
console.log(Number.EPSILON); // 2.220446049250313e-16
자바스크립트는 IEE754를 따라서 숫자(실수, 부동소수점)을 표현하고 있다. 이로 인해 2진법으로 변환 시 미세한 오차가 발생하는 구조적인 한계를 가지고 있다.
const num = 0.5 - 0.4; // 0.1이 나와야 하지만 오차 발생
console.log(num); // 0.09999999999999998
이러한 오차를 없애기 위해서 부동소수점의 연산에서는 Number.EPSILON을 사용한 함수를 만들어야 한다.
num1과 num2의 차이가 Number.EPSILON보다 작으면 같은 수로 인정할 수 있다.
function isEqual(num1, num2){
return Math.abs(num1 - num2) < Number.EPSILON;
}
console.log (isEqual(0.5 - 0.4, 0.1)) // true
const num = 12345;
console.log(num.toExponential()); // 1.2345e+4
const num = 123.45;
console.log(num.toFixed()) // 매개변수가 지정되지 않으면 기본값은 0 // 123
console.log(num.toFixed(1)); // 소수점 첫째자리까지 반올림 // 123.5
const num = 123.45678;
console.log(num.toPrecision(5)); // 123.46
console.log(num.toPrecision(6)); // 123.457