#TIL17 (2)

전혜린·2021년 8월 10일
0

Today I Learned

목록 보기
25/64

Number.prototype.toFixed()

  • toFixed() 메소드는 숫자를 고정 소수점 표기법으로 표기해 반환
  • toFixed()는 숫자데이터에 사용할 수 있는 메소드이며, 메소드가 호출될 때 인수로 소수점의 몇번째 자리까지 유지할 것인지 명시
  • toFixed 메소드가 실행되면 문자데이터가 반환됨

const pi = 3.141592
console.log(pi) //3.141592, 숫자데이터

const str = pi.toFixed(2)
console.log(str) //3.14
console.log(typeof str) //string

parseInt(), parseFloat()

  • parseInt(), parseFloat()는 자바스크립트에서 제공하는 숫자와 관련된 전역함수(global, 전체의 영역에서 언제든지 사용할 수 있는 함수)
  • 추가적으로 setTimeout, setInterval, clearTimeout, clearInterval 도 전역함수
  • parseInt(): 문자열 인자를 구문분석하여 특정 진수(수의 진법 체계에 기준이 되는 값)의 정수를 반환
  • 즉, parseInt 전역함수 부분의 인수로 문자데이터를 넣게 되면 분석 후 숫자만 추출해서 정수로 반환
  • parseFloat(): 문자열을 분석해 부동소수점 실수로 반환
  • 즉, 소수점자리의 숫자도 유지하면서 문자데이터를 숫자데이터로 변환

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

Math

  • Math는 수학적인 상수와 함수를 위한 속성과 메소드를 가진 내장 객체이며 함수 객체가 아님

Math.abs()

  • 주어진 숫자의 절대값을 반환
    console.log('abs: ', Math.abs(-12)) //abs: 12

Math.min()

  • 주어진 숫자들 중 가장 작은 값을 반환
    console.log('min: ', Math.min(2, 8)) //min: 2

Math.max()

  • 입력값으로 받은 0개 이상의 숫자 중 가장 큰 숫자를 반환
    console.log('max: ', Math.max(2, 8)) //max: 8

Math.ceil()

  • 정수단위로 올림 처리
    console.log('ceil: ', Math.ceil(3.14)) //ceil: 4

Math.floor()

  • 정수단위로 내림 처리
    console.log('floor: ', Math.floor(3.14)) //floor: 3

Math.round()

  • 정수기준으로 반올림처리
    console.log('round: ', Math.round(3.14)) //round: 3

Math.random()

  • 0 이상 1 미만의 구간에서 난수(랜덤한 숫자)를 반환
    console.log('random: ', Math.random() ) //random: 0.10729888790363962

function random() {
return Math.floor(Math.random() * 10)
}
// 무작위의 난수에 곱하기 10을 해서 내림처리함

console.log(random()) //8

profile
코딩쪼아

0개의 댓글