2-06.Math 내장 함수

2023. 3. 29. 15:37Javascript/자바스크립트 제대로 배워볼래?

<!DOCTYPE html>
<html>
<head>
    <title>Document</title>
</head>
<body>
    <script>
        // round()
        // 반올림, 반내림
        console.log(Math.round(4.9)); //5
        console.log(Math.round(4.4)); //4


        // ceil()
        // 무조건 올림으로 정수를 만듬
        console.log(Math.ceil(6.2)); //7
        console.log(Math.ceil(-4.2)); //4

        // floor()
        // 무조건 내림으로 정수를 만듬
        console.log(Math.floor(10.8)); //10
        console.log(Math.floor(-4.2)); //-5

        // trunc()
        // 정수 부분만 리턴
        console.log(Math.trunc(9.9)); //9
        console.log(Math.trunc(-4.3)); //-4

        // sign()
        // 음수이면 -1, 양수이면 1, 0이면 0
        console.log(Math.sign(-7));
        console.log(Math.sign(7));
        console.log(Math.sign(0));

        // pow()
        // 제곱
        console.log(Math.pow(8,2));

        // root()
        // 루트
        console.log(Math.sqrt(64));

        // abs()
        // 무조건 양수로 변환
        console.log(Math.abs(-4.7));

        // max(), min()
        console.log(Math.max(0, 150, 30, -50, -546, 54));
        console.log(Math.min(0, 150, 30, -50, -546, 54));

        // random()
        var x = Math.random(); // 0~1사이의 숫자 //0.9949513303438575
        console.log(x);
        // 0~<10 랜덤 숫자
        var x = Math.random()*10; // 0<x<10    //8.902157086739983
        console.log(x);
        // 0~<100 랜덤 숫자
        var x = Math.random()*100; // 0<x<100     //48.341844851557745
        console.log(x);
        // 1~100  무조건 버림으로 정수로 나타남
        var x = Math.floor(Math.random()*100 + 1);
        console.log(x);


        function getRndInteger(min, max){
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        console.log(getRndInteger(10,20));
    </script>
</body>
</html>

'Javascript > 자바스크립트 제대로 배워볼래?' 카테고리의 다른 글

2-08.Window 객체  (0) 2023.03.29
2-07.JSON 객체  (0) 2023.03.29
2-05.Date 내장 함수  (0) 2023.03.29
2-04.Array 내장 함수  (0) 2023.03.29
2-03.Boolean 내장 함수  (0) 2023.03.29