본문 바로가기
JS/JavaScript 강의

[JS] 57. Bigint 타입

by GiraffePark 2023. 1. 2.

안녕하세요. 박기린 입니다.

이번에는 Bigint에 대해 설명을 하겠습니다.

 

 

Bigint

Bigint는 ES2020부터 도입된 데이터 타입입니다. Number타입처럼 숫자를 저장하는 데이터 타입이지만, Number의 숫자 저장 한도를 넘은 수까지 저장할 수 있는 데이터 타입입니다.

그래서 말 그대로 Big - integer라고 볼 수 있습니다.

 

 

 


Number의 한계

900719925470991가 Number가 나타낼 수있는 최대 숫자 입니다.

console.log(2 ** 53 - 1); // 900719925470991
console.log(Number.MAX_SAFE_INTEGER); // 900719925470991
console.log(2 ** 53 + 1); // 900719925470992 <- console 에는 올바르게 출력되지만, unsafe한 Number이다.
console.log(2 ** 53 + 2);
console.log(2 ** 53 + 3);
console.log(2 ** 53 + 4);

실행결과물

구글 크롬 개발자모드에서는 900719925470991가 넘어도 정상적으로 출력이 되지만, 굉장히 불안정한 상태의 Number라고 할 수 있습니다. 안전한 사용을 위해 Bigint를 사용해줍시다.

 

 

 


Bigint 사용법

console.log(4838430248342043823408394839483204n);
console.log(BigInt(48384302));

Bigint는 아무리 큰 수라도 모두 받아들일 수 있습니다.

BigInt()를 이용해도 되지만, 그냥 숫자 맨 뒤에 'n'을 붙여주면 간편하게 사용할 수 있습니다.

 

 

실행결과물

console 창에서도 BigInt의 맨 끝자리에는 n이 적혀있는 모습을 확인할 수 있습니다.

 

 

 

 


Bigint의 연산자

console.log(10000n + 10000n); // 20000n
console.log(36286372637263726376237263726372632n * 10000000n); // 곱셈도 가능

Bigint에서도 산술연산자가 잘 작동합니다.

 

 

console.log(Math.sqrt(16n)); // <- Bigint에서는 Math 연산자가 작동하지 않는다.

하지만, Bigint에서는 Math 연산자를 사용할 수 없습니다.

 

 

 

const huge = 20289830237283728378237n;
const num = 23;
console.log(huge * num) // <- Error

Number와 Bigint를 같이 계산하면 에러가 발생합니다.

 

 

 


Bigint 연산자의 Exceptions - Type Coercion

console.log(typeof 20n); // bigint
console.log(20n > 15); // true - type coercion
console.log(20n === 20); // false - 등호가 세 개면 type coercion이 안 일어난다.
console.log(20n == '20'); // true - 등호가 두 개면 type coercion이 작동한다.

원래 Bigint와 Number은 함께 계산이 되지 않지만, type coercion이 일어나는 연산자일 경우 연산이 가능합니다.

 

 

 

const huge = 20289830237283728378237n;
console.log(huge + ' is REALLY big!!!'); // bigint도 자동으로 string으로 변환된다.

그리고 Bigint도 String으로 type coercion이 일어납니다.

 

 

 


Bigint의 나눗셈

console.log(10n / 3n); // 3n
console.log(11n / 3n); // 3n
console.log(10 / 3);

Bigint에서 나누기를 하면, 소수점 이하 자릿수를 전부 잘라낸 값을 return 합니다.

 

 

반응형