본문 바로가기

Dev/JAVASCRIPT

Javascript JS 숫자, 수학 메소드 (Number, Math)

//toString() 문자열변환/10진수 => 2진수/16진수 변환
let num = 10;
let convertNum = num.toString(2); // 2진수로 변환한 문자열
console.log(convertNum);

let num2 = 255;
let convertNum2 = num2.toString(16); // 16진수로 변환한 문자열
console.log(convertNum2);

//Math.ceil() 올림
let num3 = 5.7;
let num4 = 5.1;
console.log(Math.ceil(num3));

//Math.floor() 내림
console.log(Math.floor(num3));

//Math.round() 반올림
console.log(Math.round(num3));
console.log(Math.round(num4));

//소수점 n 번째 자리에서 반올림
let userRate = 30.1234;
let firstSolution = Math.round(userRate * 100)/100
let secondSolution = Number(userRate.toFixed(2));
console.log(firstSolution);
console.log(secondSolution);

//parseInt()
let margin = '10px';
console.log(parseInt(margin)); // 숫자로 시작하면 읽을수 있는 숫자는 모두 읽음 결과 10

//parseFloat() 소숫점까지 반환

//Math.random() 0~1 사이 무작위 숫자 생성
// 1~100 사이 임의의 숫자를 랜덤으로
console.log(Math.floor(Math.random()*100)+1);

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

//Math.abs() 절대값

//Math.pow(n, m) n의 m제곱

//Math.sqrt() 제곱근 ex) Math.sqrt(16) 루트 16 = 4