Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : String Functions : number_format

number_format

Format a number with grouped thousands (PHP 4, PHP 5)
string number_format ( float number [, int decimals [, string dec_point, string thousands_sep]] )

Example 2423. 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,235

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

?>

Related Examples ( Source code ) » number_format





Code Examples / Notes » number_format

dwhitaker

You know sometimes we forget to add the basic cool stuff...
Found this over in the money_format section and felt some newbie is probably looking for it...
$val = "1000000";
echo number_format($val, 0, "", ","); // returns 1,000,000


venimus777

You could use the following regular expression to divide
a number into parts:
$1-number without fractal part
$2-fractal part
$3-first 2 digits of the fractal part
$4-rest of the fractal part
the regex removes any leading and trailing symbols and leading zeros. It doesnt validate the number, so 12 41 is considered to be correct input!
english notation:
/^.*?[0]*([\d\s]+)(([\.][\d]{0,2})([\d]*))?.*?$/
french notation:
/^.*?[0]*([\d\s]+)(([\,][\d]{0,2})([\d]*))?.*?$/
<?php
// truncate the fractal part up to 2 digits of an "english number":
$number = '01,234.50789';
$trunc = preg_replace(
   '/^.*?[0]*([\d\,]+)(([\.][\d]{0,2})([\d]*))?.*?$/',
   '$1$3',
   $number
);
echo $trunc;
?>
Outputs:
1,234.50
$number='e00012 41.100001e-4fasfd';
would output:
12 41.10


cruzf_at_fibertel.com.ar

You could add padding zeros like this:
<?
$number="129";
$number=sprintf("%08d",$number);
?>


jarratt

With one of the payment providers they required a monitary input of 12345.67 always with a 2 decimal placing even if .00
if you have a number 12345.5 with only one decimal place i could find no sutable php function to guarentee two decimal palces and add a trailing zero if required,
This fucntion should assist
function format_number($str,$decimal_places='2',$decimal_padding="0"){
       /* firstly format number and shorten any extra decimal places */
       /* Note this will round off the number pre-format $str if you dont want this fucntionality */
       $str           =  number_format($str,$decimal_places,'.','');     // will return 12345.67
       $number       = explode('.',$str);
       $number[1]     = (isset($number[1]))?$number[1]:''; // to fix the PHP Notice error if str does not contain a decimal placing.
       $decimal     = str_pad($number[1],$decimal_places,$decimal_padding);
       return (float) $number[0].'.'.$decimal;
}
/* examples */
format_number('1234');       // -->   1234.00
format_number('1234.5');     //-->   1234.50
format_number('1234.567');  //-->   1234.57


steve neill

why go to all that trouble?
date('S', mktime(0,0,0,1,$str,2000));
works just as well!


tonywebman

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.


woodynadobhar

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];
};
};


astrolox

Users should be aware of the following behaviour.
I'm not sure if this is a PHP bug, libc bug, or if it's even a bug at all. So I thought I'd make a comment and allow everyone else to make up their own minds.
FreeBSD 4.3 PHP 4.3.3
<?php
// the comments show the output generated by this script
echo "input 8.525 output = ". number_format( 8.525, 2, '.', "") ."\n";
echo "input 8.525 output = ". number_format(8.525, 2, '.', "") ."\n";
// input 8.525 output = 8.53
// input 8.525 output = 8.53
$a = 483.00;
$b = 0.175;
$c = $a * $b;
echo "input \$c = $c type ". gettype($c) ." output = ". number_format( $c, 2, '.', "") ."\n";
// input $c = 84.525 type double output = 84.52
$d = 17.5;
$e = ( $a / 100 ) * $d;
echo "input \$e = $e type ". gettype($e) ." output = ". number_format( $e, 2, '.', "") ."\n";
// input $e = 84.525 type double output = 84.53
echo "input 63.745 output = ". number_format(63.745, 2, '.', "") ."\n";
echo "input 64.745 output = ". number_format(64.745, 2, '.', "") ."\n";
echo "input 65.745 output = ". number_format(65.745, 2, '.', "") ."\n";
// input 63.745 output = 63.74
// input 64.745 output = 64.75
// input 65.745 output = 65.75
?>


26-aug-2006 12:45

Unfortunately, this function is not multibyte-safe. If you want to use the typographically correct separator for thousands in Swiss German and UTF-8 (‘ - Unicode 2019), you'll only get the first byte - e.g. garbage -  since this function strips anything after the first byte, regardless of the charset used.

brandonprudent

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

eb1024

To address the problems number_format has when dealing with big numbers I've created my own Number_Format method, it acts the same way as number_format and takes the same arguments but deals with numbers as strings solving the problems above referred.
(The other methods are available at http://www.alixaxel.com/wordpress/2007/05/19/php-math-library/)
function Number_Format($number, $decimal_precision = 0, $decimals_separator = '.', $thousands_separator = ',')
{
if ($this->Is_Negative($number))
{
   $negative = true;
   $number = str_replace('-', '', $number);
}
$number = explode('.', str_replace(' ', '', $number));
$number[0] = str_split(strrev($number[0]), 3);
$total_segments = count($number[0]);
for ($i = 0; $i < $total_segments; $i++)
{
   $number[0][$i] = strrev($number[0][$i]);
}
$number[0] = implode($thousands_separator, array_reverse($number[0]));
if ($negative === true)
{
   $number[0] = '-' . $number[0];
}
if (!empty($number[1]))
{
   $number[1] = $this->Round($number[1], $decimal_precision);
}
$number = implode($decimals_separator, $number);
return $number;
}
I hope this is useful for someone!


webmaster

This is a simple and useful function to convert a byte number in a KB  or MB:
<?
function filesize_format ($bytes) {
 $bytes=(float)$bytes;
 if ($bytes<1024){
 $numero=number_format($bytes, 0, ',', '.')." Byte";
 return $numero;
 }
 if ($bytes<1048576){
 $numero=number_format($bytes/1024, 2, ',', '.')." KByte";
 return $numero;
 }
 if ($bytes>=1048576){
 $numero=number_format($bytes/1048576, 2, ',', '.')." MByte";
 return $numero;
 }
}
?>


mircea

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;
}


mikro_at_teppisti_dot_it

This function formats numbers 'human readable' better (IMHO) than mircea way:
function humanReadable($val,$thousands=0){
  if($val>=1000)
    $val=humanReadable($val/1024,++$thousands);
  else{
    $unit=array('','K','M','T','P','E','Z','Y');
    $val=round($val,2).$unit[$thousands].'B';
  }
  return $val;
}


j-a-n

This function formats an decimal number to a String.
But it does'n use an fixed count of decimals but calculates the needed count of decimals.
<?
function formatNumber( $number, $decimals=2, $dec_point=".", $thousands_sep=",") {
$nachkomma = abs($in - floor($in));
$strnachkomma = number_format($nachkomma , $decimals, ".", "");
for ($i = 1; $i <= $decimals; $i++) {
if (substr($strnachkomma, ($i * -1), 1) != "0") {
break;
}
}

   return number_format($in, ($decimals - $i +1), $dec_point, $thousands_sep);
}
?>
Example:
formatNumber( 100.00 );
--> 100
formatNumber( 100.50 );
--> 100.5
formatNumber( 100.1234 );
--> 100.12
formatNumber( 100.12, 4 );
--> 100.12
formatNumber( 100.12345, 4 );
--> 100.1234


geekprices dot com

this also works as well
$number = "29346.99"; //value
echo "$" .number_format($number, 2, '.', ',');
produces $29,346.99


04-jun-2006 08:55

The modification to number_format below does what I actually want it to do, with currency, for example. I want it to show $1.40 and not $1.4 or $1.400 - except in the rare case where I have $1.435 for something, in which case I *don't* want it to round. The ugliness below serves my purpose.
function nof($number,$decimals) {
if (number_format($number,$decimals,'.',',') != $number) {
       return $number;
} else {
       return number_format($number,$decimals,'.',',');
       }
}


user

The following function converts a string into Float or Integer while taking the given or locale number format into account.
<?php
function strtonumber( $str, $dec_point=null, $thousands_sep=null )
{
if( is_null($dec_point) || is_null($thousands_sep) ) {
$locale = localeconv();
if( is_null($dec_point) ) {
$dec_point = $locale['decimal_point'];
}
if( is_null($thousands_sep) ) {
$thousands_sep = $locale['thousands_sep'];
}
}
$number = (float) str_replace($dec_point, '.', str_replace($thousands_sep, '', $str));
if( $number == (int) $number ) {
return (int) $number;
} else {
return $number;
}
}
?>


gfinale

Thanks to armstrong ~~at~~ rice ~~dot~~ edu for your number to words function.  There does seem to be one glitch I've discovered, at least on my system.  Hundreds work but hundreds of thousands and hundreds of millions do not.  e.g. 100,000 or 100,000,000 hangs.

mike

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 */
?>


zulisse

simpler function to convert a number in bytes, kilobytes....
<?php
function bytes($a) {
$unim = array("B","KB","MB","GB","TB","PB");
$c = 0;
while ($a>=1024) {
$c++;
$a = $a/1024;
}
return number_format($a,($c ? 2 : 0),",",".")." ".$unim[$c];
}
?>
you may also add others units over PeraBytes when the hard disks will reach 1024 PB :)


marc dot vanwoerkom

See also the documentation for localeconv, which will provide values for decimal point and thousands separator from the C standard library.
Of course localeconv features many more locale information, like indicating to put the negative sign behind the value for some locale settings which can't be used to customize present number_format.


andrew

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


chandu

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);
?>


sctemplarknight

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.



ie. <input type="text" value="<?php echo(number_format(2.5343,2,".","")">


rudie

number_format is pretty fast. It's much slower than calculation though:
<?php
$start = microtime(true);
echo "<pre>";
for ($i=0;$i<100000;$i++)
{
echo number_format(microtime(true)-$start,25)."\n";
}
echo "<hr />Parsetime: ".(microtime(true)-$start);
?>
This takes 1.03 seconds all the time. Without the -$start in the number_format cmd, it takes exactly as long (I ran it about 20 times).
The simple calculation inside number_format takes relatively no time. Defining the number before entering it into number_format also gives no change:
{
$num = microtime(true)-$start;
echo number_format($num,25)."\n";
}
Which concludes it takes about .01 sec to do a thousand number_format.
If you'd do the same routine without the number_format, it'd take .75 seconds -> number_format very fast!


sgj

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


adnan 'at' barakatdesigns 'dot' net

Just a note to the author of the "zerofill" function, you may find it easier using the str_pad function
<?php
$num = 4;
$zerofill = 3;
echo str_pad($num, $zerofill, "0", STR_PAD_LEFT);
/* Returns the same wanted result of '004' */
?>


yumyum

Jarrat's example below has a problem.  If the number is negative, the sign is dropped.  It always returns positive numbers.  The problem seems to be in the float cast in:
return (float) $number[0].'.'.$decimal;
I have not had a problem in PHP5 with:
return $number[0].'.'.$decimal;


aj

In responce to astrolox;
This is because the numbers generated by performing math are double precision (which means pretty darn accurate) and not perfect precision (which would be what you get when you do the math on paper). For example 483.00 * 0.175 equals 84.525 on paper, but the computer can't do math with perfect precision and ends up with something like 84.52499999...
If dealing with money the best practice is to perform round() on your floating point numbers and always round up to the nearest cent, or add something small like .000001 before using number_format(). Personally I prefer to round().


jeroen de bruijn nl

If you want to display a number ending with ,- (like 200,-) when there are no decimal characters and display the decimals when there are decimal characters i use:
function DisplayDouble($value)
 {
 list($whole, $decimals) = split ('[.,]', $value, 2);
 if (intval($decimals) > 0)
   return number_format($value,2,".",",");
 else
   return number_format($value,0,".",",") .",-";
 }


keyg

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));
?>


svein tjonndal sveint

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>


s. rahmel

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.


j dot bos

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.


lathem

I've discovered that the commas which number_format() inserts as a thousands separators causes math functions to break.  
Bit of a newbie thing, but it bit me in the ass.
eg--
<?
$foo = number_format(1234, 2);
?>
$foo is now equal to 1,234.00
<?
$bar = 23;
$result = $foo+$bar;
?>
One would think $result == 1,257.00.  However, because number_format added a comma to $foo, the expression will not evaluate correctly.  
Instead, do things in this order:
<?
$foo=1234;
$bar=23;
$foobar=number_format($foo+$bar, 2);
?>
$foobar is now set to 1,257.00.
Another method, if you're fixing code you've already written and don't want to change a huge amount, is to remove the thousands separator, using the appropriate variable to number_format.  
<?
$foo = number_format(1234, 2, '.', '');
$bar = number_format(23, 2, '.', '');
$foobar = number_format($foo+$bar, 2);
?>
$foobar will now be set to 1,257.00


chronofish

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


ted

I use the following to get around the negative zero problem:
function currency_format($amount, $precision = 2, $use_commas = true, $show_currency_symbol = false, $parentheses_for_negative_amounts = false)
{
/*
** An improvement to number_format.  Mainly to get rid of the annoying behaviour of negative zero amounts.
*/
$amount = (float) $amount;
// Get rid of negative zero
$zero = round(0, $precision);
if (round($amount, $precision) == $zero) {
$amount = $zero;
}

if ($use_commas) {
if ($parentheses_for_negative_amounts && ($amount < 0)) {
$amount = '('.number_format(abs($amount), $precision).')';
}
else {
$amount = number_format($amount, $precision);
}
}
else {
if ($parentheses_for_negative_amounts && ($amount < 0)) {
$amount = '('.round(abs($amount), $precision).')';
}
else {
$amount = round($amount, $precision);
}
}

if ($show_currency_symbol) {
$amount = '$'.$amount;  // Change this to use the organization's country's symbol in the future
}
return $amount;
}


armstrong ~~at~~ rice ~~dot~~ edu

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


stm555

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];
     }
?>


theo diem

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


marcm

For Zero fill - just use the sprintf() function
$pr_id = 1;
$pr_id = sprintf("%03d", $pr_id);
echo $pr_id;
//outputs 001
-----------------
$pr_id = 10;
$pr_id = sprintf("%03d", $pr_id);
echo $pr_id;
//outputs 010
-----------------
You can change %03d to %04d, etc.


shpoffo .a.t.. g mail ...

For those that need to print the word-form of a number ("twenty-three" instead of "23") I've found the following code to be useful.  This code is an improvement upon that posted in 2004 by armstrong @ rice.  Notably, the previous code did not properly compute large numbers (at least in PHP 4.x that I tested).  
The following code adds another variable to the function, which controls the display of fractional parts, and properly calculates values one thousand and above.
Zak
~ ~ ~
function num2words($num, $c=1) {
$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 = num2words($remdr, 0);
  }
  $s = $t." ".$groupName[$i]." ".$s;
  $num = (int)$num;
} // end for
$s = trim($s);
if ( $negative ){
  $s = $MINUS . " " . $s;
}

if ($c == 1) $s .= " and $cents/100";

return $s;
} // end num2words


alx

enjoy the PHP!
<?php
function FormatPrice($price) {
$price = preg_replace("/[^0-9\.]/", "", str_replace(',','.',$price));
if (substr($price,-3,1)=='.') {
$sents = '.'.substr($price,-2);
$price = substr($price,0,strlen($price)-3);
} elseif (substr($price,-2,1)=='.') {
$sents = '.'.substr($price,-1);
$price = substr($price,0,strlen($price)-2);
} else {
$sents = '.00';
}
$price = preg_replace("/[^0-9]/", "", $price);
return number_format($price.$sents,2,'.','');
}
?>


jason johnson

Beware of this pitfall:
$value = number_format ($float_val, 2, ".");
This will silently return an empty string and not throw an error, at least with PHP 5.x.
This is the corrected code:
$value = number_format ($float_val, 2, ".", ",");
- or -
$value = number_format ($float_val, 2);
You must specifiy either the decimal point AND thousands separator else neither, otherwise you'll run into this issue.
I just spent over 30min debugging code with this problem!


sprille

as response to mike at phpeeb dot com.
You can do aritmetic even on strings, you just need a little function to sort it out like this :
function str2no($number){
 $number = str_replace(".", "", $number);
 $number = str_replace(",", ".", $number);
 return $number;
}
function no2str($number){
 $number = number_format($number,2, ',', '.');
 return $number;
}
 
echo no2str(str2no("1.200,50")*3);
// we use 1200.50 as input "1.200,50" is the danish string for this number
//this will output 3601.50 with right formatting = 3.601,50 as string
//nice to know when dealing with money.


jeremylujan

apparently I didn't know how str_pad works.
function zerofill ($num,$zerofill) {
   return str_pad($num,$zerofill,'0',STR_PAD_LEFT);
}


joeri

Aj and astrolox, for perfect precision arithmetic, you can use the bcmath functions, which perform math on string representations of numbers, instead of on floats. Obviously this is an order of magnitude slower, but at least you don't lose any precision due to the complexities of IEEE-754.

ck

Again, the function for returning file size in human readable format, but with a tweek for displaying one decimal when size is less than 10 units.
<?php
function human_readable( $size )
{
  $count = 0;
  $format = array("B","KB","MB","GB","TB","PB","EB","ZB","YB");
  while(($size/1024)>1 && $count<8)
  {
      $size=$size/1024;
      $count++;
  }
  if( $size < 10 ) $decimals = 1;
  else $decimals = 0;
  $return = number_format($size,$decimals,'.',' ')." ".$format[$count];
  return $return;
}
?>
Thanks to "php dot net at alan-smith dot no-ip dot com" and "service at dual-creators dot de".


steve neill

actually, you'd want to MOD the number to get it within a useful range first (1 .. 30).
Enjoy.


giovanni dot cappellini

About the function of j-a-n at gmx dot de: it's useful, but the argument of the function is $number while the logic of the function requires it to be $in.

kolnedra

A way to let a number (in this case an ammount of money) be shown in dutch annotation:
<?
// geld(123) >>> 123
// geld(123456) >>> 1.234.567
function geld($nm) {
for ($done=strlen($nm); $done > 3;$done -= 3) {
$returnNum = ".".substr($nm,$done-3,3).$returnNum;
}
return substr($nm,0,$done).$returnNum;
}
?>


uliciadrian01

A simple funtion to format american dollars.
<?
function formatMoney($money) {
if($money<1) {
$money='&cent;'.$money*100;
}
else {
$dollars=intval($money);
$cents=$money-$dollars;
$cents=$cents*100;
$money='$'.$dollars.' and &cent;'.$cents;
}
return $money;
}
echo formatmoney('52.342');
?>
This will output: "   $52 and ¢34.2  ".


drew

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


versae arroba gmail punto com

A modification for kolnedra's function
<?
function humanReadable($val, $miles = 0){
if($val>=1000)
$val = humanReadable($val / 1024, ++$miles);
else {
$unidad = array('','K','M','G','T','P','E','Z','Y',
'X','W','V','U','TD','S','R',
'Q','PP','O','N','MI','L');
$val = round($val, 2).$unidad[$miles].'B';
}
return $val;
}
?>


20-jan-2006 08:48

A function to return a number with needed zeros at the beginning. Called "zerofill"
<?php
// $num = 4; $zerofill= 3; returns "004"
function zerofill ($num,$zerofill) {
while (strlen($num)<$zerofill) {
$num = "0".$num;
}
return $num;
}
?>


php

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.


chris_cember

// the mktime shortcut is a little trickier than it would first appear, even with a mod...
function text_number($n) {
   $mod = $n % (($n > 20)?10:20);
   return $n . (($mod==0)?"th":date("S",mktime(0,0,0,1,$mod,2000)));
}  
// or for those who don't appreciate shorthand:
function text_number($n) {
   if ($n > 20) {
       $mod_factor = 10;
   } else {
       $mod_factor = 20;
   }  
   $mod = $n % $mod_factor;
   if ($mod == 0) {
       $txt = "th";
   } else {
       $txt = date("S",mktime(0,0,0,1,$mod,2000));
   }  
   return $n . $txt;
}
/*
one issue comes up in numbers that mod to zero (which mktime will associate with the 31st of December, 1999).  another issue is between 23rd and 13rd, err I mean 13th.  If you use 20 (or even 30) all the time, however, you'll end up with 33th (or 43th).
*/


mikesabatino

<?php
# Function to represent a number like '2nd', '10th', '101st' etc
function text_number($n)
{
# Array holding the teen numbers. If the last 2 numbers of $n are in this array, then we'll add 'th' to the end of $n
$teen_array = array(11, 12, 13, 14, 15, 16, 17, 18, 19);

# Array holding all the single digit numbers. If the last number of $n, or if $n itself, is a key in this array, then we'll add that key's value to the end of $n
$single_array = array(1 => 'st', 2 => 'nd', 3 => 'rd', 4 => 'th', 5 => 'th', 6 => 'th', 7 => 'th', 8 => 'th', 9 => 'th', 0 => 'th');

# Store the last 2 digits of $n in order to check if it's a teen number.
$if_teen = substr($n, -2, 2);

# Store the last digit of $n in order to check if it's a teen number. If $n is a single digit, $single will simply equal $n.
$single = substr($n, -1, 1);

# If $if_teen is in array $teen_array, store $n with 'th' concantenated onto the end of it into $new_n
if ( in_array($if_teen, $teen_array) )
{
$new_n = $n . 'th';
}
# $n is not a teen, so concant the appropriate value of it's $single_array key onto the end of $n and save it into $new_n
elseif ( $single_array[$single] )
{
$new_n = $n . $single_array[$single];
}

# Return new
return $new_n;
}
?>


Change Language


Follow Navioo On Twitter
addcslashes
addslashes
bin2hex
chop
chr
chunk_split
convert_cyr_string
convert_uudecode
convert_uuencode
count_chars
crc32
crypt
echo
explode
fprintf
get_html_translation_table
hebrev
hebrevc
html_entity_decode
htmlentities
htmlspecialchars_decode
htmlspecialchars
implode
join
levenshtein
localeconv
ltrim
md5_file
md5
metaphone
money_format
nl_langinfo
nl2br
number_format
ord
parse_str
print
printf
quoted_printable_decode
quotemeta
rtrim
setlocale
sha1_file
sha1
similar_text
soundex
sprintf
sscanf
str_getcsv
str_ireplace
str_pad
str_repeat
str_replace
str_rot13
str_shuffle
str_split
str_word_count
strcasecmp
strchr
strcmp
strcoll
strcspn
strip_tags
stripcslashes
stripos
stripslashes
stristr
strlen
strnatcasecmp
strnatcmp
strncasecmp
strncmp
strpbrk
strpos
strrchr
strrev
strripos
strrpos
strspn
strstr
strtok
strtolower
strtoupper
strtr
substr_compare
substr_count
substr_replace
substr
trim
ucfirst
ucwords
vfprintf
vprintf
vsprintf
wordwrap
eXTReMe Tracker