[실전 자바스크립트]5. number타입

주수호·2021년 2월 17일
0

[javascript]

목록 보기
4/10

문자열로 부터 숫자 파싱하기

//정수파싱
console.log(Number.parseInt('123')); //123
console.log(Number.parseInt('123.456')); //123
console.log(Number.parseInt('123abc')); //123

//실수파싱
console.log(Number.parseFloat('123')); //123
console.log(Number.parseFloat('123.456')); //123.456
console.log(Number.parseFloat('123abc')); //123
console.log(Number.parseFloat('123.456.789')); //123.456

숫자가 전혀 없는 문자열에 대한 파싱

const v = Number.parseInt('abc');
console.log(v); //NaN(Not a Number)

//NaN을 검사해주는 기능도 있다.
console.log('v', Number.isNaN(v)); // true
console.log('123', Number.isNaN(123)); // false

0으로 나눌 때에 자바스크립트

const v = 1/0;
console.log(v); //에러가 나지 않고, Infinity(자바스크립트에서 표현하는 무한)

console.log('Infinity', v === Infinity); // Infinity는 전역변수로 노출되어져 있기에 비교가능.
//값이 유한한지 검사하는 함수 또한 존재한다.
console.log('Number.isFinite', Number.isFinite(v));

number에 대한 상세 속성

자바 스크립트는 64비트 부도 소수점 방식을 사용한다(floating point)
부호(sign) 1 bit, 지수부(exponent) 11 bit, 가수부(fraction) 52 bits
(-1)^부호 가수부 2^지수부
53 bits precision
-(2^53 - 1) ~ (2^53 -1) // 안전한 정수의 범위
약 16자리의 10진수
자바스크립트 number는 단일의 형태라서 사용하기에는 편하지만, 메모리 최적화에는 어려움이 있다.

console.log(Math.pow(2, 53)-1);
console.log(Number.MIN_SAFE_INTEGER);
console.log(Number.MAX_SAFE_INTEGER);

//물론 해당 범위외의 거대한 숫자를 활용 할 수 있지만, 속성값에 의해(가수부) 정확도가 떨어지게 된다.

isSafeInteger라는 함수를 통해서 해당 숫자가 안전한 범위에 있는지 체크하는 것 또한 가능하다.

console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER));
console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1));
console.log(90071992544740995 - 10); // ......끝의자리가 6이 나온다. 안전하지 않은 숫자를 사용하지 않은 경우에는 이렇게 정확한 결과를 보장 할 수 없다.
console.log(90071992544740995n - 10n); // 위의 해결 방법을 bigint를 활용하여 해결 할 수 있다. 다음과 같이 bigint를 사용하면 정답이 나오게 된다.

const a = 90071992544740995;
const b = 10;
const resultmin = a - b; // 안전하게 나타남

//이런식으로 연산에 사용되어진 숫자들에 대해서 검사를 하는 방법도 있다.
console.log(
	Number.isSafeInteger(a), // false
  	Number.isSafeInterger(b), // true
  	Number.isSafeInteger(result); // true
);
console.log('90071992544740995 - 10 =', result); // 위 boolean값에 따라, 연산 결과를 옳다고 말할 수 없다.

const a = 90071992544740991;
const b = 10;
const resultmin = a - b; // 안전하게 나타남

//이런식으로 연산에 사용되어진 숫자들에 대해서 검사를 하는 방법도 있다.
console.log(
	Number.isSafeInteger(a), // true
  	Number.isSafeInterger(b), // true
  	Number.isSafeInteger(result); // true
);
console.log('90071992544740995 - 10 =', result); // 위 boolean값에 따라, 연산 결과를 옳다.
/* 만약 a + b를한다면
최대 숫자 값을 넘어서기 때문에 result가 false가 되어지고, 
정확한 결과를 확인 할 수 없다.*/ 
console.log(0.1 + 0.2 === 0.3); // javacript number타입은 부동소수점 방식을 사용하고 있고, 정확도 한계가 있다. 결과는?? false가 나오게 된다. 비트표현의 한계 때문에 생기는현상
console.log(0.1 + 0.2); // 실제로는 0.3........4 이런식으로 나온다.

실수의 연산에서의 EPSILON활용 비교

console.log(Number.EPSILON); //아주아주 작은 값이라고만 이해하자.
function isSimilar(x,y) {
	return Math.abs(x - y) < Number.EPSILON;
}
console.log(isSimilar(0.1 + 0.2, 0.3)); // true (표현하자면 비슷하다..)

Math객체에서의 여러 함수 알아보기

console.log(Math.random()); // 0보다는 크고 1보다는 작은 숫자를 반환해주는 random
console.log(Math.max(30, 10, 55)); // 입력받은 숫자중 가장 큰 숫자 반환
console.log(Math.pow(5, 3)); // 5의 3승

function getRandomInt(min, max) {
	return Math.floor(Math.random() * (max - min +1)) + min;
}
console.log(getRandomInt(0,10)); // 다른
console.log(getRandomInt(0,10)); // 결과가
console.log(getRandomInt(0,10)); // 나오겠지
profile
항상 준비하는 엔지니어

0개의 댓글