본문 바로가기
핀테크 서비스 프론트엔드 개발자 취업 완성 2기/JS

[JS]데이터 - 숫자(Number)와 수학(Math)

by flyda 2022. 4. 25.

1. 매소드 toFixed( ), 전역함수parseInt( ), parseFloate( )

const pi = 3.1415921231231231
console.log(pi)

const str = pi.toFixed(2)//문자열로 반환
console.log(str)//3.14
console.log(typeof str)//string

const integer = parseInt(str)//정수로 변환
const float = parseFloat(str)//소수점까지 가지는 실수로 변환
console.log(integer)//3
console.log(float)//3.14
console.log(typeof integer, typeof float)// number number 

//전역함수 Global
// setTimeout(), setInterval, clearTimeout, clearInterval 
// parseInt(),parseFloat()

참고 문서 

- toFixed() : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

 

Number.prototype.toFixed() - JavaScript | MDN

toFixed() 메서드는 숫자를 고정 소수점 표기법(fixed-point notation)으로 표시합니다.

developer.mozilla.org

- parseFloate() : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/parseFloat

 

parseFloat() - JavaScript | MDN

parseFloat() 함수는 주어진 값을 필요한 경우 문자열로 변환한 후 부동소수점 실수로 파싱해 반환합니다.

developer.mozilla.org

mdn 문서를 보니까 원래 parseInt()랑 parseFloat()는 Number.parseFloat()처럼 매소드로 쓰이다가 전역으로 추가된 것 같다!! 

 

2. Math 

절대값, 최소값, 최대값, 올림, 내림, 반올림,  랜덤을 살펴볼 것이다! 

console.log('abs : ', Math.abs(-12)) //12 //절대값
console.log('min : ', Math.min(55, 3)) //3 //최소값
console.log('max : ', Math.max(55, 2)) //55 //최대값
console.log('ceil : ', Math.ceil(55, 2)) //55 //정수 단위로 올림처리!!!// 주어진 숫자보다 크거나 같은 숫자 중 가장 작은 숫자를 integer 로 반환
console.log('floor : ', Math.floor(3.1414)) //3 //정수 단위로 내림처리!!!// 함수는 주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환
console.log('round : ', Math.round(3.1414)) //3 /반올림 // 입력값을 반올림한 수와 가장 가까운 정수 값을 반환
console.log('ramdom : ', Math.random())

 

이전에 getRandom.js라는 파일에서 만든 함수가 있다.

export default function random() {
  return Math.floor(Math.random() * 10 ) //0 ~ 9 사이의 수를 랜덤하게 얻어내는 함수
}

이제 이 코드는 Math.random( ) 으로 랜덤하게 뽑힌 수에 10을 곱해서 0. XXXX ~ 9. XXXX 로 수를 만들고 floor 매소드로 내림해서 0~9 사이의 정수를 랜덤하게 출력하는 함수로 이해할 수 있다!! 

댓글