PHP 8.1.20 Released!

number_format

(PHP 4, PHP 5, PHP 7, PHP 8)

number_formatFormata um número com os milhares agrupados

Descrição

number_format(float $number, int $decimals = ?): string
number_format(
    float $number,
    int $decimals,
    string $dec_point,
    string $thousands_sep
): string

number_format() retorna uma versão formatada de number. Esta função aceita um, dois ou quatro parâmetros (não três):

Se apenas um parâmetro é dado, number será formatado sem decimais, mas com uma virgula (",") entre cada grupo de milhar.

Se dois parâmetros são dados, number será formatado com o número de casas decimais especificadas em decimals com um ponto (".") na frente, e uma vírgula (",") entre cada grupo de milhar.

Se todos os quatro parâmetros forem dados, number será formatado com o número de casas decimais em decimals, dec_point ao invés do ponto (".") antes das casas decimais e thousands_sep ao invés de uma vírgula (",") entre os grupos de milhares.

Somente o primeiro caractere de thousands_sep é usado. Por exemplo, se você usar foo como o parâmetro thousands_sep no número 1000, number_format() irá retornar 1f000.

Exemplo #1 Exemplo number_format()

Por exemplo, a notação Francesa usa duas casas decimais, vírgula (',') como separador decimal, e espaço (' ') como separador de milhar. Isto é feito com a linha :

<?php

$number
= 1234.56;

// Notação Inglesa (padrão)
$english_format_number = number_format($number);
// 1,234

// Notação Francesa
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// Notação Inglesa com separador de milhar
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

Veja também: sprintf(), printf() e sscanf().

add a note

User Contributed Notes 9 notes

up
392
thomas at weblizards dot de
14 years ago
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
up
5
info at ensostudio dot ru
1 year ago
Note: use NumberFormatter to convert in human-readable format instead  user function from comments:
<?php
echo NumberFormatter::create('en', NumberFormatter::SPELLOUT)->format(12309); // twelve thousand three hundred nine
echo NumberFormatter::create('ru', NumberFormatter::SPELLOUT)->format(12307.5); //  двенадцать тысяч триста семь целых пять десятых
?>
up
2
Jeroen de Bruijn [NL]
17 years ago
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,".",",") .",-";
  }
up
36
james at bandit dot co.nz
14 years ago
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
up
21
MarcM
17 years ago
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.
up
15
stm555 at hotmail dot com
18 years ago
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];
      }
?>
up
4
Theo Diem
20 years ago
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
up
0
support at piri dot sk
1 month ago
My simpler solution to the problem of the decimal number in this function being longer than the specified number of decimals.

Standard result for number_format() is..
number_format(5.00098, 2) = 5.00

My function will return the result = 5.001

<?php

// ** Warning: Does not work with scientific notation. Conversion to a real number is required. **

echo auto_decimal_format(5.0005620); // print 5.0006
echo auto_decimal_format(5.0009820); // print 5.001
echo auto_decimal_format(5.00098, 8); // print 5.00098000
echo auto_decimal_format(1.0295691366783E-5, 2); // print 0.00

function auto_decimal_format($n, $def = 2) {
   
$a = explode(".", $n);
    if (
count($a)>1) {
       
$b = str_split($a[1]);
       
$pos = 1;
        foreach (
$b as $value) {
            if (
$value != 0 && $pos >= $def) {
               
$c = number_format($n, $pos);
               
$c_len = strlen(substr(strrchr($c, "."), 1));
                if (
$c_len > $def) { return rtrim($c, 0); }
                return
$c; // or break
           
}
           
$pos++;
        }
    }
    return
number_format($n, $def);
}

?>
up
1
liviu andrei (bls)
11 years ago
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!
To Top