search for in the  
<nl2brord>
Last updated: Thu, 19 May 2005

number_format

(PHP 3, PHP 4, PHP 5)

number_format -- Format a number with grouped thousands

Description

string number_format ( float number [, int decimals [, string dec_point, string thousands_sep]] )

number_format() returns a formatted version of number. This function accepts either one, two or four parameters (not three):

If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.

If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.

If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.

Only the first character of thousands_sep is used. For example, if you use foo as thousands_sep on the number 1000, number_format() will return 1f000.

Example 1. number_format() Example

For instance, French notation usually use two decimals, comma (',') as decimal separator, and space (' ') as thousand separator. This is achieved with this line :

<?php

$number
= 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,234

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

See also: sprintf(), printf() and sscanf().



User Contributed Notes
number_format
woodynadobhar at hotmail dot com
17-May-2005 11:04
What do you do if some of your numbers have decimal places, and some don't?  You can switch between functions, but if you're building it in a loop, that's not a good solution.  Instead, we have the same as below, with a slight change:

function number_format_unlimited_precision($number,$decimal = '.'){
   $broken_number = explode($decimal,$number);
   if($broken_number[1]==0){
       return number_format($broken_number[0]);
   }else{
       return number_format($broken_number[0]).$decimal.$broken_number[1];
   };
};
stm555 at hotmail dot com
27-Apr-2005 10:54
I ran across an issue where I wanted to keep the entered precision of a real value, without arbitrarily rounding off what the user had submitted.

I figured it out with a quick explode on the number before formatting. I could then format either side of the decimal.

<?php
    
function number_format_unlimited_precision($number,$decimal = '.')
     {
          
$broken_number = explode($decimal,$number);
           return
number_format($broken_number[0]).$decimal.$broken_number[1];
     }
?>
mike at phpeeb dot com
02-Apr-2005 03:13
Since number_format returns a string, you must perform all mathmatical functions on the number before applying number_format:

<?
$total
= 100;
$total = number_format($total, 2);
$shipping = 20.00;
$grand_total = $total + $shipping;

echo
number_format($grand_total, 2);

/* The above will return 21.00 because $total is now a string, and no longer an integer or float. Since a string will have a value of 1,  the addition of the two will return 21 and not 120. */

$total = 100;
$shipping = 20.00;
$grand_total = $total + $shipping;

echo
number_format($grand_total, 2);

/* This works, and will return 120.00 as intended */

?>
php at mijav dot dk
31-Mar-2005 08:25
A bug was issued that -0,00 is invalid output from number_format(), but the bug was rejected since the number "-0.0000000000000000001E-999 is about -0". And the developer felt this was correct output.

Please beware of negative numbers close to zero, as they might produce this unusable (and in my opinion incorrect/off-description) output.
ChronoFish
23-Mar-2005 01:14
I was looking for an easy way to take a number (or string) and force into a specific format.  I came up with.  I apologize if this is redundant, but I could not find a simular function:

/***********************************
* string_format
***********************************/
function string_format($format, $string, $placeHolder = "#")
{           
   $numMatches = preg_match_all("/($placeHolder+)/", $format, $matches);             
   foreach ($matches[0] as $match)
   {
       $matchLen = strlen($match);
       $format = preg_replace("/$placeHolder+/", substr($string, 0, $matchLen), $format, 1);
       $string = substr($string, $matchLen);
   }
   return $format;
}

To Use:

print string_format("(###)###-####", "4015551212");
will print out:
(401)555-1212

Hope this helps someone,

CF
tonywebman at NOSPAM dot telusplanet dot net
23-Feb-2005 03:14
While trying to add variables whose values had been processed with number_format() I found an interesting gotcha. Perhaps this might help others.

Since number_format() returns a string, numbers returned that DO NOT have a comma in them will still be added but numbers that DO have a comma will not be added because PHP considers them a string and ignores them.

e.g. #1
$quant_mag = 1;
$cost_mag = 100;
$quant_ffr = 1
$cost_ffr = 100;

$ext_mag = number_format($quant_mag * $cost_mag,2);
$ext_ffr = number_format($quant_ffr * $cost_ffr,2);

$total_cost = $ext_mag + $ext_ffr;

// $total cost is: 200

e.g. #2
$quant_mag = 10;
$cost_mag = 100;
$quant_ffr = 1
$cost_ffr = 100;

$ext_mag = number_format($quant_mag * $cost_mag,2);
$ext_ffr = number_format($quant_ffr * $cost_ffr,2);

$total_cost = $ext_mag + $ext_ffr;
// $total cost is: 100 (not 1100 as you would expect) because $ext_mag is ignored because php interprets its value (1,000) as a string so it won't add it to $ext_ffr.
keyg at auralplanet dot com
22-Nov-2004 08:56
if you want &nbsp; as a separator and use windows charset this piece of code may help:

<?php
$number
=number_format($number,2,'.',chr(0xA0));
?>
brandonprudent at yahoo dot com
10-Oct-2004 01:52
To convert numbers to thier textual representations, you can use an adapted version of the Number::Spell Perl module. The PHP conversion can be found here: http://pear.php.net/package/Numbers_Words
GeekPrices Dot Com
06-Oct-2004 07:57
this also works as well

$number = "29346.99"; //value
echo "$" .number_format($number, 2, '.', ',');

produces $29,346.99
Svein Tjonndal (sveint at yahoo dot com)
14-Sep-2004 09:18
If you use space as a separator, it will break on that space in HTML tables...

Furthermore, number_format doesn't like '&nbsp;' as a fourth parameter. I wrote the following function to display the numbers in an HTML table.

  function numberfix($number)
  {
   $number = number_format($number,0,","," ");
   return str_replace(" ", "&nbsp;", $number);
  }

For use in:
<table><tr><td><?php echo $number; ?></td></tr></table>
drew at zitnay dot com
17-Aug-2004 01:17
A more reliable and concise way of doing what S. Rahmel was trying to do below is as follows:

<?php
$field_inhalt
= str_replace(array(".", ","), array("", "."), $field_inhalt);
?>

The str_replace() call will first replace all dots with blanks, and then replace all commas with dots.  That way, it doesn't break down when you try a number over one million (i.e. 1.010.453,21).

Drew
mircea at vtds dot co dot uk
02-Jun-2004 11:57
This function formats numbers 'human readable':

function byte_format($input, $dec=0)
{
  $prefix_arr = array(" B", "K", "M", "G", "T");
  $value = round($input, $dec);
  $i=0;
  while ($value>1024)
  {
     $value /= 1024;
     $i++;
  }
  $return_str = round($value, $dec).$prefix_arr[$i];
  return $return_str;
}
S. Rahmel
11-Mar-2004 04:47
if you converted a number to a German format with number_format() and want to save it in mySQL, you first have to change the number format back to an English format.

For example
10.453,21 >>>> 10453.21

Here is an example how to do this:

   $field_array=explode(".", $field_inhalt);
   $field_inhalt=$field_array[0].$field_array[1];
   $foeld_array=explode(",", $field_inhalt);
   $field_inhalt=$field_array[0].".".$feld_array[1];
   $field_inhalt=sprintf($field_inhalt, 2);

$field_inhalt is the variable of the actual number you want to change to the english format.
chandu at chandu dot org
07-Mar-2004 07:29
People here in India are more used to counting money in Lakhs & Crores .. so here is the code for formatting the commas with thousands for the first time and then with hundred multiples from there after.

Ex: 1234567  ->  12,34,567

<?php

function makecomma($input)
{
  
// This function is written by some anonymous person - I got it from Google
  
if(strlen($input)<=2)
   { return
$input; }
  
$length=substr($input,0,strlen($input)-2);
  
$formatted_input = makecomma($length).",".substr($input,-2);
   return
$formatted_input;
}

function
formatInIndianStyle($num){
  
// This is my function
  
$pos = strpos((string)$num, ".");
   if (
$pos === false) { $decimalpart="00";}
   else {
$decimalpart= substr($num, $pos+1, 2); $num = substr($num,0,$pos); }

   if(
strlen($num)>3 & strlen($num) <= 12){
              
$last3digits = substr($num, -3 );
              
$numexceptlastdigits = substr($num, 0, -3 );
              
$formatted = makecomma($numexceptlastdigits);
              
$stringtoreturn = $formatted.",".$last3digits.".".$decimalpart ;
   }elseif(
strlen($num)<=3){
              
$stringtoreturn = $num.".".$decimalpart ;
   }elseif(
strlen($num)>12){
              
$stringtoreturn = number_format($num, 2);
   }

   if(
substr($stringtoreturn,0,2)=="-,"){$stringtoreturn = "-".substr($stringtoreturn,2 );}

   return
$stringtoreturn;
}

$num = 1234567;
echo 
formatInIndianStyle($num);

?>
armstrong ~~at~~ rice ~~dot~~ edu
23-Feb-2004 06:33
I submitted this question earlier, but I found the answer myself.  To convert a number to its word form (e.g. 34 to "thirty four")  try the function below.  It turned out to be a lot more complex than I thought!

I'm using it for printing dollar ammounts, so the cents get printed like 13/100

I converted most of it from this java code http://mindprod.com/inwords.html so credit goes to him for doing the hard part.

<?
/**
* convert long integer into American English words.
* e.g. -12345 -> "minus twelve thousand forty-five"
* Handles negative and positive integers
* on range -Long.MAX_VALUE .. Long.MAX_VALUE;
* It cannot handle Long.MIN_VALUE;
*/

function num2words( $num ){
  
$ZERO = "zero";
  
$MINUS = "minus";
  
$lowName = array(
        
/* zero is shown as "" since it is never used in combined forms */
         /* 0 .. 19 */
        
"", "one", "two", "three", "four", "five",
        
"six", "seven", "eight", "nine", "ten",
        
"eleven", "twelve", "thirteen", "fourteen", "fifteen",
        
"sixteen", "seventeen", "eighteen", "nineteen");

  
$tys = array(
        
/* 0, 10, 20, 30 ... 90 */
        
"", "", "twenty", "thirty", "forty", "fifty",
        
"sixty", "seventy", "eighty", "ninety");

  
$groupName = array(
        
/* We only need up to a quintillion, since a long is about 9 * 10 ^ 18 */
         /* American: unit, hundred, thousand, million, billion, trillion, quadrillion, quintillion */
        
"", "hundred", "thousand", "million", "billion",
        
"trillion", "quadrillion", "quintillion");

  
$divisor = array(
        
/* How many of this group is needed to form one of the succeeding group. */
         /* American: unit, hundred, thousand, million, billion, trillion, quadrillion, quintillion */
        
100, 10, 1000, 1000, 1000, 1000, 1000, 1000) ;

  
$num = str_replace(",","",$num);
  
$num = number_format($num,2,'.','');
  
$cents = substr($num,strlen($num)-2,strlen($num)-1);
  
$num = (int)$num;

  
$s = "";

   if (
$num == 0 ) $s = $ZERO;
  
$negative = ($num < 0 );
   if (
$negative ) $num = -$num;

  
// Work least significant digit to most, right to left.
   // until high order part is all 0s.
  
for ( $i=0; $num>0; $i++ ) {
      
$remdr = (int)($num % $divisor[$i]);
      
$num = $num / $divisor[$i];
      
// check for 1100 .. 1999, 2100..2999, ... 5200..5999
       // but not 1000..1099,  2000..2099, ...
       // Special case written as fifty-nine hundred.
       // e.g. thousands digit is 1..5 and hundreds digit is 1..9
       // Only when no further higher order.
      
if ( $i == 1 /* doing hundreds */ && 1 <= $num && $num <= 5 ){
           if (
$remdr > 0 ){
              
$remdr += $num * 10;
              
$num = 0;
           }
// end if
      
} // end if
      
if ( $remdr == 0 ){
           continue;
       }
      
$t = "";
       if (
$remdr < 20 ){
          
$t = $lowName[$remdr];
       }
       else if (
$remdr < 100 ){
          
$units = (int)$remdr % 10;
          
$tens = (int)$remdr / 10;
          
$t = $tys [$tens];
           if (
$units != 0 ){
              
$t .= "-" . $lowName[$units];
           }
       }else {
          
$t = $inWords($remdr);
       }
      
$s = $t . " " . $groupName[$i] . " "  . $s;
      
$num = (int)$num;
   }
// end for
  
$s = trim($s);
   if (
$negative ){
      
$s = $MINUS . " " . $s;
   }

  
$s .= " and $cents/100";

   return
$s;
}
// end inWords

?>
cruzf_AT_fibertel.com.ar
07-Nov-2003 01:03
You could add padding zeros like this:

<?
$number
="129";
$number=sprintf("%08d",$number);
?>
j dot bos at bytewriters dot nl
01-Jun-2003 02:45
If I'm not mistaking all these examples of adding leading zeros will not really work with floats. Sometimes though one needs it to have it working with floats as well.

With the function below use 2, 3 or 5 parameters. Don't ask me why 4 don't work, the number_format() function seems to have problems with that. At least my version of PHP has that "feature".

function leading_zero( $aNumber, $intPart, $floatPart=NULL, $dec_point=NULL, $thousands_sep=NULL) {        //Note: The $thousands_sep has no real function because it will be "disturbed" by plain leading zeros -> the main goal of the function
  $formattedNumber = $aNumber;
  if (!is_null($floatPart)) {    //without 3rd parameters the "float part" of the float shouldn't be touched
   $formattedNumber = number_format($formattedNumber, $floatPart, $dec_point, $thousands_sep);
   }
  //if ($intPart > floor(log10($formattedNumber)))
   $formattedNumber = str_repeat("0",($intPart + -1 - floor(log10($formattedNumber)))).$formattedNumber;
  return $formattedNumber;
  }

echo leading_zero(21.12345678, 4, 5);    // Output: 0021.12346
echo leading_zero(21.12345678, 4);    // Output: 0021.12345678
echo leading_zero(21.12345678, 3, 0); // Output: 021
echo leading_zero(21.12345678, 3, 5, ",", ""); // Output: 021,12346

addition: Just like the number_format I haven't found a way *not* to round a number while changing the decimal point and the thousands seperator.
sgj at dr dot com
17-May-2003 08:04
Just an observation:
The number_format rounds the value of the variable.

$val1 = 1.233;
$val2 = 1.235;
$val3 = 1.237;

echo number_format($val1,2,",","."); // returns: 1,23
echo number_format($val2,2,",","."); // returns: 1,24
echo number_format($val3,2,",","."); // returns: 1,24
Theo Diem
24-Mar-2003 03:45
formatting numbers may be more easy if u use number_format function.

I also wrote this :
function something($number)
{
   $locale = localeconv();
   return number_format($number,
       $locale['frac_digits'],
       $locale['decimal_point'],
       $locale['thousands_sep']);
}

hope this helps =)
[]'s
andrew at crucible dot co dot nz
04-Jan-2002 06:56
Remember that number_format returns a string, so you shouldn't run a number_format on a variable that's already a product of number_format (it will only take the first token of the string)...

eg. echo number_format("123,456.00", 2);
produces: 123.00
sctemplarknight at hotmail dot com
12-Dec-2001 03:27
number_format($number,$precision,".","") should be used when setting the value of form elements because if you read the number into a double upon submission, it will only store digits before the comma.
<p>
ie. <input type="text" value="<?php echo(number_format(2.5343,2,".","")">

<nl2brord>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT