JS 중급 | 숫자, 수학 method (Number, Math)

uoah·2023년 1월 12일
0

자바스크립트

목록 보기
20/33
post-thumbnail

🚀 오늘의 학습 목표

  • 숫자 (Number) method
  • 수학 (Math) method

5. Number, Math

5-1. Number

5-1-1. toString

10진수를 2진수 또는 16진수르 변환할 때 toString 을 사용한다.

10진수 -> 2진수 / 16진수

let num = 10;

num.toString();		// "10"
num.toString(2); 	// "1010"

let num2 = 255;
num2.toString(16); 	// "fF"

5-2. Math

수학과 관련된 프로퍼티와 메서드들을 갖고 잇는 내장 객체로 Math 가 있다.

대표적인 프로퍼티 예로 Math.PI (원주율) 가 있다.

let num = Math.PI;

console.log(num);	//3.141592653589793

그 외 몇 가지를 더 알아 보자.

5-2-1. Math.ceil() 올림

let num1 = 5.1;
let num2 = 5.7;

console.log(Math.ceil(num1)); // 6
console.log(Math.ceil(num2)); // 6

5-2-2. Math.floor() 내림

let num1 = 5.1;
let num2 = 5.7;

console.log(Math.floor(num1)); // 5
console.log(Math.floor(num2)); // 5

5-2-3. Math.round() 반올림

let num1 = 5.1;
let num2 = 5.7;

console.log(Math.round(num1));	// 5
console.log(Math.round(num2));	// 6

5-2-4. 소수점 자릿수

📌 요구 사항 : 소수점 둘째 자리 까지 표현 (셋째 자리에서 반올림)

let userRate = 30.1234;

방법 1

(1)

userRate * 100; //3012.34

(2)

Math.round(userRate * 100); // 3012

(3)

Math.round(userRate * 100) / 100; // 30.12

방법 2. toFixed()

(1)

userRate.toFixed(2); // "30.12" 

숫자를 인수로 받아 그 숫자 만큼 소수점 이하 개수에 반영한다.
훨씬 간단하게 값을 출력할 수 있다.

만약, 소수 0이거나 기존 소수점 개수보다 큰 경우는 어떻게 될까?

userRate.toFixed(0); // "30"
userRate.toFixed(2); // "30.123400"

단, 주의할 점은 toFixed() 메서드는 문자열을 반환하기 때문에 다시 사용할 때 Number 숫자로 자료형을 변환하여 사용한다.

let userRate = 30.1234;

console.log(userRate.toFixed(2)); // "30.12"
console.log(Number(userRate.toFixed(2))); // 30.12

5-2-5. isNaN()

let x = Number('x'); // NaN

NaN 인지 아닌지를 판단할 수 있는 것은 isNaN 만이 유일하다.

let x = Number('x');

console.log(x);	// NaN

console.log(x == NaN);		// false
console.log(x === NaN);		// false
console.log(NaN == NaN);	// false

console.log(isNaN(x));	// true
console.log(isNaN(3));	// false

5-2-6. parseInt()

parseInt() 는 읽을 수 있는 만큼은 최대한 읽고 문자열을 숫자로 바꿔 준다.

let margin = '10px';

console.log(parseInt(margin));	//10
console.log(Number(margin));	//NaN

let redColor = 'f3';
console.log(parseInt(redColor)); //NaN

숫자가 아닌 문자열이 먼저 나올 경우 NaN 을 반환한다.

❗️ 그런데, 두 번째 인수를 받아서 진수를 지정할 수 있다.

console.log(parseInt(redColor, 16)); // 243
console.log(parseInt('11',2)); // 3

5-2-7. parseFloat()

pasresFloat()은 parseInt와 동일하게 작동하지만 부동소수점을 반환한다.

let padding = '18.5%';

console.log(parseInt(padding)); // 18
console.log(parseFloat(padding)); // 18.5

5-2-8. Math.random()

0~1 사이 무작위 숫자를 생성한다.

Math.random() //0.48536869787143666
Math.random() //0.2978214656247469
Math.random() //0.6089418733547307
Math.random() //0.4775160938176384

그래서 만약 1~100 사이 임의의 숫자를 뽑고 싶다면? 아래와 같이 식을 사용하여 구해야 한다.

console.log(Math.floor(Math.random()*100)+1);

풀이

(1) Math.random() : 0~1 사이의 무작위 숫자를 생성한다. (위의 예제에서는 0.6789)

(2) *100 : 0.6789 에서 100 을 곱한다. (1~100 사이의 수를 구해야 하기 때문에)
💬 만약, 1 ~ 5 사이의 숫자를 구하는 것이라면 *5를 하면 된다.

(3) Math.floor() : 소수점을 내림하여 없앤다.

(4) +1 : 만약 소수점 자리를 내렸을 때 0이 나올 수 있기 때문에 최소값 1을 더한다.

5-2-9. Math.max() / Math.min()

Math.max(1, 3, 5, 6, -1, 45, 3, 4.5, 20); // 10
Math.min(1, 3, 5, 6, -1, 45, 3, 4.5, 20); // -1

Math.max() 최대값
Math.min() 최소값

5-2-10. Math.abs() 절대값

abs 는 absolute 의 약자이다.

Math.abs(-1); // 1

5-2-11. Math.pow(n, m) 제곱

n 의 m 승값, 즉 제곱값을 구해 준다.
pow 는 power 의 약자이다.

console.log(Math.pow(2, 10)); // 1024

5-2-12. Math.sqrt() 제곱근 (루트)

루트값을 구해 준다.
sqrt 는 square root 의 약자이다.

console.log(Math.sqrt(16)); // 4

0개의 댓글

관련 채용 정보