★ wanayoo — archive 1999 http://fr.php.net/manual/it/function.number-format.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<nl2brord>
view the version of this page
Last updated: Wed, 24 Nov 2004

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 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.

Esempio 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().



add a note add a note User Contributed Notes
number_format
keyg at auralplanet dot com
23-Nov-2004 03: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 08: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
07-Oct-2004 02: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)
15-Sep-2004 04: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 08: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 06: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 11: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
08-Mar-2004 02: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 01: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 08:03
You could add padding zeros like this:

<?
$number
="129";
$number=sprintf("%08d",$number);
?>
j dot bos at bytewriters dot nl
01-Jun-2003 09: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
18-May-2003 03: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 10: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
05-Jan-2002 01: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 10: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: Wed, 24 Nov 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Fri Nov 26 05:15:47 2004 CET