Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript Number.toFixed() 함수 완벽 가이드 – 고정 소수점 표기법

Number 객체의 toFixed() 함수는 소수점 이하 몇 자리까지 표시할지를 나타내는 숫자를 인수로 전달받아, 해당 자릿수만큼 반올림된 고정 소수점(fixed-point) 표기법의 문자열을 반환합니다.

문법(Syntax)

num.toFixed(num);

인수 num에는 0부터 100 사이의 정수를 지정할 수 있습니다. 값을 생략하면 기본값 0으로 처리되어 소수점 이하가 제거됩니다. 또한 반환 결과는 항상 문자열(String) 타입이라는 점에 유의해야 하며, 수치 연산이 필요하다면 parseFloat() 등으로 변환해야 합니다.

예제 1

<html>
<head>
    <title>JavaScript Example</title>
</head>
<body>
    <script type="text/javascript">
        var num = Math.PI;
        result = num.toFixed(4);
        document.write("Fixed point notation of the given number is: " + result);
    </script>
</body>
</html>

실행 결과

Fixed point notation of the given number is: 3.1416

위 예제에서는 Math.PI(약 3.141592653589793) 값에 대해 toFixed(4)를 호출했습니다. 소수점 네 번째 자리까지만 표시하도록 지정했기 때문에, 다섯 번째 자리에서 반올림된 3.1416이 출력됩니다.

예제 2

<html>
<head>
    <title>JavaScript Example</title>
</head>
<body>
    <script type="text/javascript">
        var num = Math.PI;
        document.write("Fixed point notation of the given number is: " + num.toFixed(4));
        document.write("<br>");
        var num = 2.13e+15;
        document.write("Fixed point notation of the given number is: " + num.toFixed(4));
    </script>
</body>
</html>

실행 결과

Fixed point notation of the given number is: 3.1416
Fixed point notation of the given number is: 2130000000000000.0000

두 번째 예제처럼 지수 표기법으로 표현된 매우 큰 숫자(2.13e+15)에도 toFixed(4)를 적용하면, 지수 형태 대신 소수점 넷째 자리까지 포함한 일반적인 고정 소수점 형태인 2130000000000000.0000으로 변환되어 출력됩니다.

활용 팁

toFixed()는 금액 표시, 통계 수치 출력 등 소수 자릿수를 일정하게 맞춰야 하는 상황에서 특히 유용합니다. 다만 반올림 방식은 부동소수점 연산의 한계로 인해 미세하게 다르게 동작할 수 있으므로, 금융 계산처럼 높은 정밀도가 필요한 경우에는 별도의 처리 로직을 함께 고려하는 것이 좋습니다.