개요
- number_format() 함수는 숫자를 지정된 형식에 맞춰 문자열로 변환하는 데 사용됩니다. 이 함수는 특히 숫자를 자릿수에 따라 콤마(쉼표)로 구분하거나 소수점을 지정할 때 유용합니다.
 
- PHP 4 이상에서 사용할 수 있습니다.
 
문법
number_format( num, decimals, decimal_separator, thousands_separator )
- num : 변환할 숫자입니다.
 
- decimals : 표시할 소수점 이하 자리 수입니다. 기본값은 0으로, 소수점을 표시하지 않습니다.
 
- decimal_separator : 소수점 구분자로 사용할 문자를 지정합니다. 기본값은 "."입니다.
 
- thousands_separator : 천 단위 구분자로 사용할 문자를 지정합니다. 기본값은 ","입니다.
 
예제 1
<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>PHP</title>
    <style>
      body { 
        font-family: Consolas, monospace;
      }
    </style>
  </head>
  <body>
    <p>
      number_format( 123456.123456 ) :
      <?php echo number_format( 123456.123456 ); ?>
    </p>
    <p>
      number_format( 123456.123456, 1 ) :
      <?php echo number_format( 123456.123456, 1 ); ?>
    </p>
    <p>
      number_format( 123456.123456, 2 ) :
      <?php echo number_format( 123456.123456, 4 ); ?>
    </p>
  </body>
</html>

예제 2
- 문자열이어도 숫자로 이루어진 것이라면 작동합니다. 빈 문자열은 아무것도 출력하지 않지만, NULL은 0을 반환합니다.
 
<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>PHP</title>
    <style>
      body { 
        font-family: Consolas, monospace;
      }
    </style>
  </head>
  <body>
    <p>
      number_format( '123456.123456' ) :
      <?php echo number_format( '123456.123456' ); ?>
    </p>
    <p>
      number_format( '' ) :
      <?php echo number_format( '' ); ?>
    </p>
    <p>
      number_format( NULL ) :
      <?php echo number_format( NULL ); ?>
    </p>
  </body>
</html>
