본문 바로가기
Mechanic: IT 인터넷/Mechanic, M-Tech

JavaScript 소수점 자리수 고정 - toFixed() 사용법과 주의점

by M-LOG : 엠로그 2014. 10. 7.
반응형

원본 작성일: 2014.10.07
보완 작성일: 2026.02.14

JavaScript toFixed 소수점 자리수 고정

JavaScript에서 소수점 자리수를 고정해서 표시할 때 toFixed()를 쓴다. 간단한 메서드지만 몇 가지 함정이 있다.

기본 사용법

const num = 1234;
num.toFixed(2);    // "1234.00"

const pi = 3.14159;
pi.toFixed(2);     // "3.14"
pi.toFixed(4);     // "3.1416" (반올림됨)

const small = 0.5;
small.toFixed(3);  // "0.500"

toFixed(n): 소수점 n번째 자리까지 표시. 부족하면 0으로 채우고, 초과하면 반올림한다.

주의점 1: 반환 타입은 문자열

const price = 19.9;
const result = price.toFixed(2);

typeof result;       // "string"
result + 1;          // "19.901" (문자열 연결!)
Number(result) + 1;  // 20.9    (숫자 연산)

toFixed()문자열을 반환한다. 연산에 쓰려면 Number()parseFloat()로 변환해야 한다.

주의점 2: 부동소수점 반올림 함정

(1.005).toFixed(2);   // "1.00" (기대: "1.01")
(0.615).toFixed(2);   // "0.61" (기대: "0.62")

IEEE 754 부동소수점 표현 문제 때문에, 일부 숫자에서 반올림이 기대와 다르게 동작한다. 정확한 반올림이 필요하면:

function roundFixed(num, decimals) {
    return (Math.round(num * Math.pow(10, decimals)) / Math.pow(10, decimals)).toFixed(decimals);
}

roundFixed(1.005, 2);  // "1.01"

금액 표시에는 Intl.NumberFormat

통화나 금액을 표시하는 용도라면 Intl.NumberFormat이 더 적합하다.

const formatter = new Intl.NumberFormat('ko-KR', {
    style: 'currency',
    currency: 'KRW'
});

formatter.format(15000);  // "₩15,000"

// 소수점 자리수 지정
const usd = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
});

usd.format(19.9);  // "$19.90"

정리

상황 추천 방법
단순 소수점 자리수 표시 toFixed()
계산 결과 반올림 Math.round() + toFixed() 조합
금액/통화 표시 Intl.NumberFormat

관련 글: JavaScript 반올림, 올림, 내림 - Math.round, ceil, floor 자리수 지정

반응형