ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JS] 소수점 자릿수 반올림
    JavaScript 2023. 4. 15. 10:56
    반응형
    SMALL

     

     

     

    자바스크립트
    소수점 반올림


     

     

     

    Math.round() 소수점 반올림 
    4이하의 수는 버리고 5이상의 수는 윗자리에 1을 더하는 방법
    console.log(Math.round(0.4)) // 0
    
    console.log(Math.round(0.5)) // 1

     

     

     

     

     

    Math.ceil() 소수점 올림 
    0이 아닌 숫자가 있을 경우 구하려는 자리의 숫자를 1만큼 크게 하고 나머지 수는 모두 버린다. 0.1~0.9를 올림 하면 1이 된다.
    console.log(Math.ceil(0.1)) //1
    
    console.log(Math.ceil(0.9)) //1

     

     

     

     

     

    Math.floor() 소수점 내림
    자리의 숫자가 무엇이든 그 자리 이하 숫자를 0으로 바꾸는것을 의미한다. 0.1~0.9를 내림하면 0이 된다.
    console.log(Math.floor(1.1)) //1
    
    console.log(Math.floor(1.98)) //1

     

     

     

     

     

    Number.toFixed() 
    소수점을 특정 자릿수 기준으로 반올림이 필요한 경우에는 Number객체가 가지고 있는 toFixed() 함수를 사용할 수 있다.
    const number = 12345.6789;
    
    console.log(number.toFixed(3)) //12345.678
    
    console.log(number.toFixed(1)) //12345.6 : 반올림한다.
    
    console.log(number.toFixed(6)) //12345.67899 : 빈 공간을 0으로 채운다.
    
    2.34.toFixed(1);        // Returns '2.3'
    
    2.35.toFixed(1);        // Returns '2.4'. 이 경우에는 올림을 합니다.

     

     

     

     

    반응형
    LIST

    'JavaScript' 카테고리의 다른 글

    [JS] at 인덱스 요소 반환  (0) 2023.04.14
    [JS] 몫과 나머지 구하기  (0) 2023.04.13
    [JS] async function  (0) 2022.12.20
    [JS] keydown, keyup, keypress  (0) 2022.12.07
    [JS] focus, blur Event  (0) 2022.12.06

    댓글

Designed by Tistory.