Documentation on number_format

number_format = Format a number with grouped thousands

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.

Usage, params, and more on number_format

string number_format ( float $number [, int $decimals = 0 ] )

number The number being formatted. decimals Sets the number of decimal points. dec_point Sets the separator for the decimal point. thousands_sep Sets the thousands separator.

A formatted version of number.

Notes and warnings on number_format

Basic example of how to use: number_format

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,235

// French notation
$nombre_format_francais number_format($number2','' ');
// 1 234,56

$number 1234.5678;

// english notation without thousands separator
$english_format_number number_format($number2'.''');
// 1234.57

?>

Other code examples of number_format being used

<?php

$number 
1234.56;

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

// French notation
$nombre_format_francais number_format($number2','' ');
// 1 234,56

$number 1234.5678;

// english notation without thousands separator
$english_format_number number_format($number2'.''');
// 1234.57

?>

It's not explicitly documented; number_format also rounds:

<?php
$numbers
= array(0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009);
foreach (
$numbers as $number)
    print
$number."->".number_format($number, 2, '.', ',')."<br>";
?>

0.001->0.00
0.002->0.00
0.003->0.00
0.004->0.00
0.005->0.01
0.006->0.01
0.007->0.01
0.008->0.01
0.009->0.01

Outputs a human readable number.

<?php
   
#    Output easy-to-read numbers
    #    by james at bandit.co.nz
   
function bd_nice_number($n) {
       
// first strip any formatting;
       
$n = (0+str_replace(",","",$n));
       
       
// is this a number?
       
if(!is_numeric($n)) return false;
       
       
// now filter it;
       
if($n>1000000000000) return round(($n/1000000000000),1).' trillion';
        else if(
$n>1000000000) return round(($n/1000000000),1).' billion';
        else if(
$n>1000000) return round(($n/1000000),1).' million';
        else if(
$n>1000) return round(($n/1000),1).' thousand';
       
        return
number_format($n);
    }
?>

Outputs:

247,704,360 -> 247.7 million
866,965,260,000 -> 867 billion

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

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>

In my function my_number_format() [shown below] there was a bug.

If a negative number which is smaller than 1 was entered (-0,...), then the result was wrongly positive because +0 is equal to -0 (the content of $tmp[0] which was interpretet as numeric value).

Here is the corrected version:

<?php

function my_number_format($number, $dec_point, $thousands_sep)
{
   
$was_neg = $number < 0; // Because +0 == -0
   
$number = abs($number);

   
$tmp = explode('.', $number);
   
$out = number_format($tmp[0], 0, $dec_point, $thousands_sep);
    if (isset(
$tmp[1])) $out .= $dec_point.$tmp[1];

    if (
$was_neg) $out = "-$out";

    return
$out;
}

?>

Thanks to Federico Cassinelli for the bug report.



[EDIT BY danbrown AT php DOT net: The original note follows.]

Let's say we got the number $inp = 1234.56

By using

<?php
return number_format($inp, 2, ',', '.');
?>

you can get the German format 1.234,56. (Comma as decimal separator and point as thousand separator)

But I have a problem with that: I want to add commas as thousand separators and change the decimal-separator (this could also be done with str_replace), but I do not want to change the amount of fractional digits!

But since the 2nd argument of number_format is necessary to enter the 3rd and 4th argument, this cannot be done with number_format. You have to change the fractional digits with this function.

But I want that 1234.56 changes into 1.234,56 and 1234.567890123456 changes into 1.234,567890123456

So, I created following function, that doesn't change the amount of fractional digits:

<?php
function my_number_format($number, $dec_point, $thousands_sep)
{
 
$tmp = explode('.', $number);
 
$out = number_format($tmp[0], 0, $dec_point, $thousands_sep);
  if (isset(
$tmp[1])) $out .= $dec_point.$tmp[1];

  return
$out;
}
?>

I'm not sure if this is the right place anyway, but "ben at last dot fm"'s ordinal function can be simplified further by removing the redundant "floor" (the result of floor is still a float, it's the "%" that's converting to int) and outer switch.

Note that this version also returns the number with the suffix on the end, not just the suffix.

<?php
function ordinal($num)
{
   
// Special case "teenth"
   
if ( ($num / 10) % 10 != 1 )
    {
       
// Handle 1st, 2nd, 3rd
       
switch( $num % 10 )
        {
            case
1: return $num . 'st';
            case
2: return $num . 'nd';
            case
3: return $num . 'rd'
        }
    }
   
// Everything else is "nth"
   
return $num . 'th';
}
?>

To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people below):

<?php
function fnumber_format($number, $decimals='', $sep1='', $sep2='') {

        if ((
$number * pow(10 , $decimals + 1) % 10 ) == 5//if next not significant digit is 5
           
$number -= pow(10 , -($decimals+1));

        return
number_format($number, $decimals, $sep1, $sep2);

}

$t=7.15;
echo
$t . " | " . number_format($t, 1, '.', ',') .  " | " . fnumber_format($t, 1, '.', ',') . "\n\n";
//result is: 7.15 | 7.2 | 7.1

$t=7.3215;
echo
$t . " | " . number_format($t, 3, '.', ',') .  " | " . fnumber_format($t, 3, '.', ',') . "\n\n";
//result is: 7.3215 | 7.322 | 7.321
} ?>

have fun!

I was looking for a SIMPLE way to format currency and account for negative values while not losing the calculation properties of my number.  Here's my function - it's not rocket science, but maybe can help someone along the way.

<?php
function wims_currency($number) {
   if (
$number < 0) {
    
$print_number = "($ " . str_replace('-', '', number_format ($number, 2, ".", ",")) . ")";
    } else {
    
$print_number = "$ " number_format ($number, 2, ".", ",") ;
   }
   return
$print_number;
}
?>
Sample use:

<?php
$pur_po_total
=  ($pur_po_total + $pur_item_total);
$print_pur_po_total = wims_currency($pur_po_total);
?>

Returns (for example)    $ 44,561.00 or, if a negative ($ 407,250.00)

This way, I use my 1st variable for calculations and my 2nd variable for output.  I'm sure there are better ways to do it,  but this got me back on track.

I came into a need to show two decimal places, but the desire to drop the decimal portion off if it is zero. This function is a direct replacement for number_format:

<?PHP
function number_format_clean($number,$precision=0,$dec_point='.',$thousands_sep=',')
    {
    RETURN
trim(number_format($number,$precision,$dec_point,$thousands_sep),'0'.$dec_point);
    }
?>

Example:

<?PHP
echo number_format_clean(25.00,2);
echo
number_format_clean(25.52,2);
echo
number_format_clean(50.10,2);
echo
number_format_clean(05.50,2);
?>

Outputs:
25
25.52
50.1
5.5

Good for weight conversions (1 oz vs. 1.00 oz). Feels less "automated."

The above will trim all insignificant zeros from both ends of the string, though I'm not sure I've ever seen leading zeros returned.

This function is used for reformatting already formatted numbers.
<?php
function formatNumber($number, $format=[], $oldDecimalSeparator=",.·'", $multiplier=1)
{
   
/**
    $format — the array of formatting options, details in the example.
    $oldDecimalSeparator — decimal separator used in the $number. If the separator can meet different characters, then you need to record them all, for example: ',.'.
    $multiplier — typically used to adjust prices up or down.
    */
   
if ($format) {
       
$format += ['numOfDecimals' => 0, 'decimalSeparator' => '.', 'thousandSeparator' => '']; # Default format
        # Find decimal separator
        # The decimal separator is the one that is the last and does not occur more than once
       
if ($letters = str_replace(' ', '', $number)) { # Replace spaces
           
if ($letters = preg_replace('/^-/', '', $letters)) { # Remove minus
               
if ($letters = preg_replace('/[0-9]/', '', $letters)) { # Get all non digits
                   
$lastletter = substr($letters, -1); # Returns last char
                   
if (substr_count($letters, $lastletter) == 1) {
                        if (
strpos($oldDecimalSeparator, $lastletter)  !== false)
                           
$oldDecimalSep = $lastletter;
                        else
                            return
$number;
                    }
                }
            }
        }
       
$number = preg_replace('/[^0-9-]/', '', $number); # Remove all non digits except 'minus'
       
if ($oldDecimalSep)
           
$number = str_replace($oldDecimalSep, '.', $number); # Format to float
       
if ($multiplier != 1)
           
$number = $number * $multiplier;
       
# Convert float to new format
       
$number = number_format($number,
           
$format['numOfDecimals'],
           
$format['decimalSeparator'],
           
$format['thousandSeparator']
        ); 
    }
    return
$number;   
}

/**
Example. Formatting data in which the decimal separator can occur as the comma and dot. Formatting into Russian format: -12 345,67
*/
echo formatNumber($number, [
   
'numOfDecimals' => 2,
   
'decimalSeparator' => ',',
   
'thousandSeparator' => '&nbsp;'
], ',.');

?>

<?php

   
function convertNumberToWordsForIndia($number){
       
//A function to convert numbers into Indian readable words with Cores, Lakhs and Thousands.
       
$words = array(
       
'0'=> '' ,'1'=> 'one' ,'2'=> 'two' ,'3' => 'three','4' => 'four','5' => 'five',
       
'6' => 'six','7' => 'seven','8' => 'eight','9' => 'nine','10' => 'ten',
       
'11' => 'eleven','12' => 'twelve','13' => 'thirteen','14' => 'fouteen','15' => 'fifteen',
       
'16' => 'sixteen','17' => 'seventeen','18' => 'eighteen','19' => 'nineteen','20' => 'twenty',
       
'30' => 'thirty','40' => 'fourty','50' => 'fifty','60' => 'sixty','70' => 'seventy',
       
'80' => 'eighty','90' => 'ninty');
       
       
//First find the length of the number
       
$number_length = strlen($number);
       
//Initialize an empty array
       
$number_array = array(0,0,0,0,0,0,0,0,0);       
       
$received_number_array = array();
       
       
//Store all received numbers into an array
       
for($i=0;$i<$number_length;$i++){    $received_number_array[$i] = substr($number,$i,1);    }

       
//Populate the empty array with the numbers received - most critical operation
       
for($i=9-$number_length,$j=0;$i<9;$i++,$j++){ $number_array[$i] = $received_number_array[$j]; }
       
$number_to_words_string = "";       
       
//Finding out whether it is teen ? and then multiplying by 10, example 17 is seventeen, so if 1 is preceeded with 7 multiply 1 by 10 and add 7 to it.
       
for($i=0,$j=1;$i<9;$i++,$j++){
            if(
$i==0 || $i==2 || $i==4 || $i==7){
                if(
$number_array[$i]=="1"){
                   
$number_array[$j] = 10+$number_array[$j];
                   
$number_array[$i] = 0;
                }       
            }
        }
       
       
$value = "";
        for(
$i=0;$i<9;$i++){
            if(
$i==0 || $i==2 || $i==4 || $i==7){    $value = $number_array[$i]*10; }
            else{
$value = $number_array[$i];    }           
            if(
$value!=0){ $number_to_words_string.= $words["$value"]." "; }
            if(
$i==1 && $value!=0){    $number_to_words_string.= "Crores "; }
            if(
$i==3 && $value!=0){    $number_to_words_string.= "Lakhs ";    }
            if(
$i==5 && $value!=0){    $number_to_words_string.= "Thousand "; }
            if(
$i==6 && $value!=0){    $number_to_words_string.= "Hundred &amp; "; }
        }
        if(
$number_length>9){ $number_to_words_string = "Sorry This does not support more than 99 Crores"; }
        return
ucwords(strtolower("Indian Rupees ".$number_to_words_string)." Only.");
    }

    echo
convertNumberToWordsForIndia("987654321");
   
   
//Output ==> Indian Rupees Ninty Eight Crores Seventy Six Lakhs Fifty Four Thousand Three Hundred & Twenty One Only.
?>

Here a function to filter exponential notation like 6e-06. Turn it to 0,000006 for comfortable reading. Supporting various number of decimals!

<?php
function easy_number_format($number, $dec_point, $thousands_sep)
{
   
$number = rtrim(sprintf('%f', $number), "0");
    if (
fmod($nummer, 1) != 0) {                     
       
$array_int_dec = explode('.', $number);
    } else {
       
$array_int_dec= array(strlen($nummer), 0);
    }
    (
strlen($array_int_dec[1]) < 2) ? ($decimals = 2) : ($decimals = strlen($array_int_dec[1]));
    return
number_format($number, $decimals, $dec_point, $thousands_sep);
}
?>

The maximum accuracy depends on sprintf('%f', $number). In this case 6 decimals. Expand it to 10 with '%.10f'.

There has been some suggestions around on how to keep trailing zeros. Best way is to use the example for currency provided by the php-crew in the sprintf function help section.

That is:
<?php
$money1
= 68.75;
$money2 = 54.35;
$money = $money1 + $money2;

// echo $money will output "123.1";

$formatted = sprintf("%01.2f", $money); // << this does the trick!

// echo $formatted will output "123.10"

?>

Some programmers may have scripts that use the number_format function twice on a variable.  However, if a number is 4 or more digits, using the function twice with only the decimals parameter will lose part of the value that follows the thousands separator.

<?php
$var
= number_format(2234,2);
$var = number_format($var,2);
echo
$var;
# Expected Output: 2,234.00
# Actual Output: 2.00
?>

To fix, remove the thousands separator by setting the decimal point and thousands separator parameters like so:

<?php
$var
= number_format(2234,2,'.','');
$var = number_format($var,2,'.','');
echo
$var;
# Expected Output: 2234.00
# Actual Output: 2234.00
?>

If it's 3 digits or less, then it works normally with only the decimals parameter since there is no thousands separator.

<?php
$var
= number_format(123,2);
$var = number_format($var,2);
echo
$var;
# Expected Output: 123.00
# Actual Output: 123.00
?>

function to convert numbers to words
indian: thousand,lakh,crore
Note: function can only convert nos upto 99 crores

<?php
$words
= array('0'=> '' ,'1'=> 'one' ,'2'=> 'two' ,'3' => 'three','4' => 'four','5' => 'five','6' => 'six','7' => 'seven','8' => 'eight','9' => 'nine','10' => 'ten','11' => 'eleven','12' => 'twelve','13' => 'thirteen','14' => 'fouteen','15' => 'fifteen','16' => 'sixteen','17' => 'seventeen','18' => 'eighteen','19' => 'nineteen','20' => 'twenty','30' => 'thirty','40' => 'fourty','50' => 'fifty','60' => 'sixty','70' => 'seventy','80' => 'eighty','90' => 'ninty','100' => 'hundred &','1000' => 'thousand','100000' => 'lakh','10000000' => 'crore');
function
no_to_words($no)
{    global
$words;
    if(
$no == 0)
        return
' ';
    else {          
$novalue='';$highno=$no;$remainno=0;$value=100;$value1=1000;       
            while(
$no>=100)    {
                if((
$value <= $no) &&($no  < $value1))    {
               
$novalue=$words["$value"];
               
$highno = (int)($no/$value);
               
$remainno = $no % $value;
                break;
                }
               
$value= $value1;
               
$value1 = $value * 100;
            }       
          if(
array_key_exists("$highno",$words))
              return
$words["$highno"]." ".$novalue." ".no_to_words($remainno);
          else {
            
$unit=$highno%10;
            
$ten =(int)($highno/10)*10;            
             return
$words["$ten"]." ".$words["$unit"]." ".$novalue." ".no_to_words($remainno);
           }
    }
}
echo
no_to_words(999978987);

?>

Writing a function to get English ordinals for numbers is a problem every computer science student will face. Here's my solution - nice, short and simple:

<?php
   
function st($i) {
        switch(
floor($i/10) % 10 ) {
            default:
                switch(
$i % 10 ) {
                    case
1: return 'st';
                    case
2: return 'nd';
                    case
3: return 'rd';  
                }
            case
1:
        }
        return
'th';
    }
?>

Simple function to show money as only dollars if no cents, but will show 2 decimals if cents exist.

The 'cents' flag can force to never or always show 2 decimals

<?php

// formats money to a whole number or with 2 decimals; includes a dollar sign in front
function formatMoney($number, $cents = 1) { // cents: 0=never, 1=if needed, 2=always
 
if (is_numeric($number)) { // a number
   
if (!$number) { // zero
     
$money = ($cents == 2 ? '0.00' : '0'); // output zero
   
} else { // value
     
if (floor($number) == $number) { // whole number
       
$money = number_format($number, ($cents == 2 ? 2 : 0)); // format
     
} else { // cents
       
$money = number_format(round($number, 2), ($cents == 0 ? 0 : 2)); // format
     
} // integer or decimal
   
} // value
   
return '$'.$money;
  }
// numeric
} // formatMoney

$a = array(1, 1234, 1.5, 1.234, 2.345, 2.001, 2.100, '1.000', '1.2345', '12345', 0, '0.00');

// show cents if needed ($cents=1)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 1));
1 = $1
1234
= $1,234
1.5
= $1.50
1.234
= $1.23
2.345
= $2.35
2.001
= $2.00
2.1
= $2.10
1.000
= $1
1.2345
= $1.23
12345
= $12,345
0
= $0
0.00
= $0

// never show cents ($cents=0)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 0));
1 = $1
1234
= $1,234
1.5
= $2
1.234
= $1
2.345
= $2
2.001
= $2
2.1
= $2
1.000
= $1
1.2345
= $1
12345
= $12,345
0
= $0
0.00
= $0

// always show cents ($cents=2)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 2));
1 = $1.00
1234
= $1,234.00
1.5
= $1.50
1.234
= $1.23
2.345
= $2.35
2.001
= $2.00
2.1
= $2.10
1.000
= $1.00
1.2345
= $1.23
12345
= $12,345.00
0
= $0.00
0.00
= $0.00

?>

Cheers :)

And remember to always contribute custom functions if they might be useful to the rest of us or future versions of the php language.

Exemplo: Example:

<?php
$number
= 1234567.896;
echo
'1: '.number_format($number, 2, ',', '').'<br>';
echo
'2: '.number_format($number, 2, '.', '').'<br>';
echo
'3: '.number_format($number, 2, ',', '.').'<br>';
echo
'4: '.number_format($number, 2, '.', ',').'<br>';
echo
'5: '.number_format($number, 2, ',', ' ').'<br>';
echo
'6: '.number_format($number, 2, ',', "'").'<br>';
echo
'7: '.number_format($number, 2, '', '').'<br>';
?>

Resultado: Result:

1: 1234567,90   -> Decimal separado por ,
2: 1234567.90   -> Decimal separado por .
3: 1.234.567,90 -> Moeda Brasil, Alemanha
4: 1,234,567.90 -> Inglês, USA
5: 1 234 567,90 -> França
6: 1'234'567,90 -> Suíça
7: 123456790    -> Sem decimal

here is the code to convert number to Indonesian text, this code has limitation as is number_format function. sorry for this.
/*
* Created : Iwan Sapoetra - Jun 13, 2008
* Project : Web
* Package : cgaf
*
*/
function terbilang( $num ,$dec=4){
    $stext = array(
        "Nol",
        "Satu",
        "Dua",
        "Tiga",
        "Empat",
        "Lima",
        "Enam",
        "Tujuh",
        "Delapan",
        "Sembilan",
        "Sepuluh",
        "Sebelas"
    );
    $say  = array(
        "Ribu",
        "Juta",
        "Milyar",
        "Triliun",
        "Biliun", // remember limitation of float
        "--apaan---" ///setelah biliun namanya apa?
    );
    $w = "";

    if ($num <0 ) {
        $w  = "Minus ";
        //make positive
        $num *= -1;
    }

    $snum = number_format($num,$dec,",",".");
    die($snum);
    $strnum =  explode(".",substr($snum,0,strrpos($snum,",")));
    //parse decimalnya
    $koma = substr($snum,strrpos($snum,",")+1);

    $isone = substr($num,0,1)  ==1;
    if (count($strnum)==1) {
        $num = $strnum[0];
        switch (strlen($num)) {
            case 1:
            case 2:
                if (!isset($stext[$strnum[0]])){
                    if($num<19){
                        $w .=$stext[substr($num,1)]." Belas";
                    }else{
                        $w .= $stext[substr($num,0,1)]." Puluh ".
                            (intval(substr($num,1))==0 ? "" : $stext[substr($num,1)]);
                    }
                }else{
                    $w .= $stext[$strnum[0]];
                }
                break;
            case 3:
                $w .=  ($isone ? "Seratus" : terbilang(substr($num,0,1)) .
                    " Ratus").
                    " ".(intval(substr($num,1))==0 ? "" : terbilang(substr($num,1)));
                break;
            case 4:
                $w .=  ($isone ? "Seribu" : terbilang(substr($num,0,1)) .
                    " Ribu").
                    " ".(intval(substr($num,1))==0 ? "" : terbilang(substr($num,1)));
                break;
            default:
                break;
        }
    }else{
        $text = $say[count($strnum)-2];
        $w = ($isone && strlen($strnum[0])==1 && count($strnum) <=3? "Se".strtolower($text) : terbilang($strnum[0]).' '.$text);
        array_shift($strnum);
        $i =count($strnum)-2;
        foreach ($strnum as $k=>$v) {
            if (intval($v)) {
                $w.= ' '.terbilang($v).' '.($i >=0 ? $say[$i] : "");
            }
            $i--;
        }
    }
    $w = trim($w);
    if ($dec = intval($koma)) {
        $w .= " Koma ". terbilang($koma);
    }
    return trim($w);
}
//example
echo terbilang(999999999999)."\n";
/**
* result : Sembilan Ratus Sembilan Puluh Sembilan Milyar Sembilan Ratus Sembilan Puluh Sembilan Juta Sembilan Ratus Sembilan Puluh Sembilan Ribu Sembilan Ratus Sembilan Puluh Sembilan
*/
echo terbilang(9999999999999999);
/**
* todo : fix this bug pleasese
* problem : number_format(9999999999999999) <--- 10.000.000.000.000.000,0000
* Result : Sepuluh Biliun
*/

Using the number_format I'm having some unexpected results.  30% of 14.95 (14.95 * .3) = 4.485.  Now 4.485 rounded to two decimal places should give me 4.49.

Example:
<?php
echo number_format(14.95 * .3, 2, '.', '') . "\n";
echo
number_format(4.485, 2, '.', '') . "\n";
?>

Unexpected Results:
4.48
4.49

I use the following to get around the negative zero problem:

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

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 :)

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

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

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

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,'.','');
}
?>