JavaScript

[Javascript] 소수점 올림, 버림, 반올림 함수 / Math.ceil(), Math.floor(), Math.round(), parseInt()

hellosonic 2023. 8. 2. 15:56

Math.ceil() : 올림

<script>
    Math.ceil(10.1); //11
    Math.ceil(10.1534); //11
    Math.ceil(-10.9); //-10
    Math.ceil(-10.919); //-10
</script>

Math.floor() : 버림

<script>
    Math.floor(10.9); //10
    Math.floor(10.919); //10
    Math.floor(-10.1); //-11
    Math.floor(-10.153) //-11
</script>

Math.round() : 반올림

<script>
    Math.round(-10.9); //-11
    Math.round(-10.919); //-11
    Math.round(10.5); //11
    Math.round(10.4); //10
</script>

숫자.toFixed(자리수) : 원하는 소수점 길이만큼만 반올림해서 반환해준다.

<script>
    var number1 = 1.34313;
    var number2 = 1.35756;
    console.log(number1.toFixed(2)); //1.34
    console.log(number2.tofixed(4)); //1.3576;
</script>

parseInt(string, radix) : 문자열을 숫자로 변환하기

  • string : 숫자로 변환할 문자열
  • radix : string 문자열을 읽을 진법 / 2~36의 수
  • string을 정수로 변환한 값을 리턴한다. 만약 string의 첫 글자를 정수로 변경할 수 없으면 NaN(Not a Number)을 리턴한다.
<script>
    console.log(parseInt("10")); // 10
    console.log(parseInt("-10")); // -10
    console.log(parseInt("10.9")); //10
    console.log(parseInt(10)); //10
    console.log(parseInt("10n")); // 10
    console.log(parseInt("10nnn13")); //10
    console.log(parseInt("     10")); //10
    console.log(parseInt("k10")); //NaN
    
    console.log(parseInt("10", 2)); // "10"을 2진법으로 읽어서, 10진법으로 변환한 값 리턴 : 2
    console.log(parseInt("2", 2)); // 2진법에는 2라는 숫자가 없으므로 NaN 리턴
</script>