update page now
Laravel Live Japan

number_format

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

number_formatFormata um número com milhares agrupados

Descrição

number_format(
    float $num,
    int $decimals = 0,
    ?string $decimal_separator = ".",
    ?string $thousands_separator = ","
): string

Formata um número com milhares agrupados e opcionalmente dígitos decimais usando a regra de arredondamento de meia unidade para cima.

Parâmetros

num

O número a ser formatado.

decimals

Define o número de dígitos decimais. Se for igual a 0, o separador de decimais definido por decimal_separator é omitido do valor de retorno. A partir do PHP 8.3.0, quando o valor é negativo, num é arredondado para o número de dígitos significativos informado em decimals antes do separador de decimais. Antes do PHP 8.3.0, valores negativos eram ignorados e manipulados como se fossem 0.

decimal_separator

Define a string separadora de decimais.

thousands_separator

Define a string separadora de milhares.

Valor Retornado

Uma versão formatada de num.

Registro de Alterações

Versão Descrição
8.3.0 Adicionada a manipulação de valores negativos para decimals.
8.0.0 Antes desta versão, number_format() aceitava um, dois ou quatro parâmetros (mas não três).
7.2.0 number_format() foi modificado para não ser capaz de retornar -0, anteriormente -0 poderia ser retornado para casos onde num fosse -0.01.

Exemplos

Exemplo #1 Exemplo de number_format()

Por exemplo, a notação francesa normalmente usa duas casas decimais, vírgula (',') como separador de decimais e espaço (' ') como separador de milhares. O exemplo a seguir demonstra várias formas de formatar um número:

<?php

$number
= 1234.56;

// notação inglesa (padrão)
echo number_format($number), PHP_EOL;
// 1,235

// notação francesa
echo number_format($number, 2, ',', ' '), PHP_EOL;
// 1 234,56

$number = 1234.5678;

// notação inglesa sem separador de milhares
echo number_format($number, 2, '.', ''), PHP_EOL;
// 1234.57

?>

Exemplo #2 Um valor negativo para decimals

A partir do PHP 8.3.0, um valor negativo para decimals é usado para arredondar o número de dígitos significativos antes do separador de decimais.

<?php
$number
= "1234.5678";
var_dump(number_format($number, -1));
var_dump(number_format($number, -2));
var_dump(number_format($number, -3));
?>

O exemplo acima produzirá:

string(5) "1,230"
string(5) "1,200"
string(5) "1,000"

Veja Também

  • money_format() - Formata um número como uma string de moeda
  • sprintf() - Retona uma string formatada
  • printf() - Envia uma string formatada para a saída
  • sscanf() - Interpreta a entrada de uma string de acordo com um formato

adicionar nota

Notas de Usuários 7 notes

up
429
thomas at weblizards dot de
16 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
41
james at bandit dot co.nz
16 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
9
info at ensostudio dot ru
3 years 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
6
Jeroen de Bruijn [NL]
20 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
8
Theo Diem
22 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
19
MarcM
19 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
13
stm555 at hotmail dot com
20 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];
      }
?>
To Top