number_format

(PHP 4, PHP 5)

number_format — Форматирует число с разделением групп

Описание

string number_format ( float $number [, int $decimals ] )
string number_format ( float $number , int $decimals , string $dec_point , string $thousands_sep )

number_format() возвращает отформатированное число number . Функция принимает один, два или четыре аргумента (не три):

Если передан только один аргумент, number будет отформатирован без дробной части, но с запятой (",") между группами цифр по 3.

Если переданы два аргумента, number будет отформатирован с decimals знаками после точки (".") и с запятой (",") между группами цифр по 3.

Если переданы все четыре аргумента, number будет отформатирован с decimals знаками после точки и с разделитилем между группами цифр по 3, при этом в качестве десятичной точки будет использован dec_point , а в качестве разделителя групп - thousands_sep .

Используется только первый символ строки thousands_sep . Например, при передаче foo в качестве thousands_sep для форматирования числа 1000, number_format() возвращает 1f000.

Пример #1 Пример использования number_format()

Во Франции обычно используются 2 знака после запятой (','), и пробел (' ') в качестве разделителя групп. Такое форматирование получается при использовании следующего кода :

<?php

$number 
1234.56;

// английский формат (по умолчанию)
$english_format_number number_format($number);
// 1,234

// французский формат
$nombre_format_francais number_format($number2','' ');
// 1 234,56

$number 1234.5678;

// английский формат без разделителей групп
$english_format_number number_format($number2'.''');
// 1234.57

?>

См. также описание функций sprintf(), printf() и sscanf().

Коментарии

Автор:
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
2003-03-24 15:45:31
http://php5.kiev.ua/manual/ru/function.number-format.html
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];
      }
?>
2005-04-27 11:54:44
http://php5.kiev.ua/manual/ru/function.number-format.html
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,".",",") .",-";
  }
2005-10-01 18:02:24
http://php5.kiev.ua/manual/ru/function.number-format.html
Автор:
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.
2006-02-21 00:03:48
http://php5.kiev.ua/manual/ru/function.number-format.html
It's not explicitly documented; number_format also rounds:

<?php
$numbers 
= array(0.0010.0020.0030.0040.0050.0060.0070.0080.009);
foreach (
$numbers as $number)
    print 
$number."->".number_format($number2'.'',')."<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
2009-01-23 07:43:14
http://php5.kiev.ua/manual/ru/function.number-format.html
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
2009-03-26 23:03:53
http://php5.kiev.ua/manual/ru/function.number-format.html
Автор:
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($t1'.'',') .  " | " fnumber_format($t1'.'',') . "\n\n";
//result is: 7.15 | 7.2 | 7.1

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

have fun!
2011-11-18 10:10:10
http://php5.kiev.ua/manual/ru/function.number-format.html
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); //  двенадцать тысяч триста семь целых пять десятых
?>
2021-12-30 22:28:22
http://php5.kiev.ua/manual/ru/function.number-format.html
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.000988); // print 5.00098000
echo auto_decimal_format(1.0295691366783E-52); // 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 != && $pos >= $def) {
               
$c number_format($n$pos);
               
$c_len strlen(substr(strrchr($c"."), 1));
                if (
$c_len $def) { return rtrim($c0); }
                return 
$c// or break
           
}
           
$pos++;
        }
    }
    return 
number_format($n$def);
}

?>
2023-04-16 03:18:49
http://php5.kiev.ua/manual/ru/function.number-format.html
Автор:
India (~18% of the world's population), Pakistan (~3%), Bangladesh (~2%), Nepal, and Myanmar, have a different way to display large numbers:

10,23,45,678.20

The first thousand is "normal" but then there is a comma every TWO digits after that.

Now look at the number_format() function.  Do you see a way to control the placement and frequency of the commas?  Or a mode option/switch to deal with displaying numbers for almost 1/4 of the total population on Earth?  Neither do I.

If you are developing an application for an international audience, the ICU-based Intl PHP extension might work fine for you.  However, IBM's ICU library is a resource heavy library (because...IBM), isn't the fastest library on the planet (also normal for IBM), ICU formatters are somewhat unreliable/inconsistent (yup, still IBM), and the Intl extension isn't always available in PHP (this one's PHP).  So there are many significant hurdles to overcome just to prepare a number for display using the Intl extension.

In short, approximately 23% of the planet currently can't use this function for displaying large numbers and there isn't a good built-in *lightweight* alternative other than to roll your own solution that outright replaces this function.  Formatting a number for display is an extremely common task.

Disclaimer:  This comment serves as a warning to others that this function isn't suitable for an international audience in its current state.  This comment is not a question, bug report, or feature request.  I'm simply commenting on the current state of affairs with this function.  If someone opts to make changes/improvements, then great, but that's not the purpose here.
2023-10-20 19:12:27
http://php5.kiev.ua/manual/ru/function.number-format.html

    Поддержать сайт на родительском проекте КГБ