PHP money_format() Function
The money_format() function returns a string formatted as a currency string.
This function inserts a formatted number where there is a percent (%) sign in the main string.
Note: The money_format() function does not work on Windows platforms.
Tip: This function is often used together with the setlocale() function.
Tip: To view all available language codes, go to our Language code reference.
Syntax
Parameter Values
Parameter | Description |
---|---|
string | Required. Specifies the string to be formatted and how to format the variables in it. |
- =f — Specifies the character (f) to be used as padding (Example: %=t this uses «t» as padding). Default is space
- ^ — Removes the use of grouping characters
- + or ( — Specifies how to show positive and negative numbers. If «+» is used, the local setting for + and — will be used (usually a sign in front of negative numbers, and nothing in front of positive numbers). If «(» is used, negative numbers are enclosed in parenthesis. Default is «+»
- ! — Stops the use of currency symbols in the output string
- — If «-» is used, all fields are left-justified. Default is right-justified
- x — Specifies the minimum field width (x). Default is 0
- #x — Specifies the maximum number (x) of digits expected to the left of the decimal point. This is used to keep formatted output aligned in the same columns. If the number of digits are bigger than x, this specification is ignored
- .x — Specifies the maximum number (x) of digits expected to the right of the decimal point. If x is 0, the decimal point and the digits to its right will not be shown. Default is local settings
- i — The number is formatted to international currency format
- n — The number is formatted to national currency format
- % — Returns the % character
Note: If multiple format values are used, they must be in the same order as shown above.
Note: This function is affected by local settings.
Technical Details
Return Value: | Returns the formatted string. Characters before and after the formatting string will be returned unchanged. Non-numeric number causes returning NULL and emitting E_WARNING |
---|---|
PHP Version: | 4.3.0+ |
More Examples
Example
International format (Germany) with 2 decimals:
The output of the code above will be:
Example
Negative number, US national format with () to indicate negative numbers and 2 digits of right precision and «*» as a fill character:
The output of the code above will be:
number_format
Formats a number with grouped thousands and optionally decimal digits using the rounding half up rule.
Parameters
The number being formatted.
Sets the number of decimal digits. If 0 , the decimal_separator is omitted from the return value.
Sets the separator for the decimal point.
Sets the thousands separator.
Return Values
A formatted version of num .
Changelog
Version | Description |
---|---|
8.0.0 | Prior to this version, number_format() accepted one, two, or four parameters (but not three). |
7.2.0 | number_format() was changed to not being able to return -0 , previously -0 could be returned for cases like where num would be -0.01 . |
Examples
Example #1 number_format() Example
For instance, French notation usually use two decimals, comma (‘,’) as decimal separator, and space (‘ ‘) as thousand separator. The following example demonstrates various ways to format a number:
// english notation (default)
$english_format_number = number_format ( $number );
// 1,235
// French notation
$nombre_format_francais = number_format ( $number , 2 , ‘,’ , ‘ ‘ );
// 1 234,56
// english notation without thousands separator
$english_format_number = number_format ( $number , 2 , ‘.’ , » );
// 1234.57
See Also
- money_format() — Formats a number as a currency string
- sprintf() — Return a formatted string
- printf() — Output a formatted string
- sscanf() — Parses input from a string according to a format
User Contributed Notes 9 notes
It’s not explicitly documented; number_format also rounds:
$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 , ‘.’ , ‘,’ ). «
» ;
?>
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
Note: use NumberFormatter to convert in human-readable format instead user function from comments:
echo NumberFormatter :: create ( ‘en’ , NumberFormatter :: SPELLOUT )-> format ( 12309 ); // twelve thousand three hundred nine
echo NumberFormatter :: create ( ‘ru’ , NumberFormatter :: SPELLOUT )-> format ( 12307.5 ); // двенадцать тысяч триста семь целых пять десятых
?>
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,».»,»,») .»,-«;
>
Outputs a human readable number.
# 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
For Zero fill — just use the sprintf() function
$pr_id = 1;
$pr_id = sprintf(«%03d», $pr_id);
echo $pr_id;
$pr_id = 10;
$pr_id = sprintf(«%03d», $pr_id);
echo $pr_id;
You can change %03d to %04d, etc.
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.
function number_format_unlimited_precision ( $number , $decimal = ‘.’ )
$broken_number = explode ( $decimal , $number );
return number_format ( $broken_number [ 0 ]). $decimal . $broken_number [ 1 ];
>
?>
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’]);
>
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
// ** 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 );
>
To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people below):
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!
money_format
money_format() форматирует число number как денежную величину. Эта функция вызывает функцию strfmon() языка C, но позволяет преобразовать только одно число за один вызов.
Список параметров
- символа %
- необязательных флагов
- необязательной ширины поля
- необязательной точности до запятой
- необязательной точности после запятой
- обязательного описателя преобразования
Флаги
Могут быть использованы следующие флаги: = f
Символ =, за которым следует еще один символ f , задает символ заполнения. По умолчанию пробел.
Отключает группировку символов (определяемую текущей локалью).
Задает способ форматирования положительных и отрицательных значений. При использовании + будут использоваться аналоги символов + и — из текущей локали. Если указана (, отрицательные числа будут заключены в скобки. По умолчанию +.
Подавляет вывод символа валюты.
Если этот флаг задан, поля будут выравнены влево (с отбивкой вправо), вместо используемого по умолчанию выравнивания вправо (с отбивкой влево).
Ширина поля
Строка из десятичных цифр, задающая минимальную ширину поля. Поле будет выравнено вправо, если не указан флаг —. Значение по умолчанию — 0 (ноль).
Точность до запятой
Максимальное количество цифр ( n ), которое ожидается до запятой. Это обычно используется при выводе значений одно под другим, чтобы десятичные точки располагались в одной колонке, при этом используется символ заполнения, если число цифр меньше n . Если число цифр больше n , этот параметр игнорируется.
Если группировка не была отключена флагом ^, разделители групп будут вставлены перед добавлением символов заполнения. Разделители групп не вставляются между символами заполнения, даже если заполнитель — цифра.
Для обеспечения выравнивания, все символы, выводимые до или после числа, такие как символ валюты или знак, будут дополнены пробелами до одинаковой ширины.
Точность после запятой
Точка, за которой следует число знаков ( p ), выводимых после запятой. Если значение p равно нулю, десятичная точка и цифры после нее не будут выводиться. Если этот параметр отсутствует, число знаков после запятой определяется текущей локалью. Перед форматированием число округляется до указанного количества знаков.
Описатель преобразования
Используется международный денежный формат из текущей локали (например, для американской локали: USD 1,234.56).
Используется национальный денежный формат из текущей локали (например, для локали de_DE: EU1.234,56).
Возвращаемые значения
Возвращает отформатированную строку. Символы перед и после описания формата возвращаются без изменений. Если number не является числом, то будет возвращен NULL и вызвана ошибка уровня E_WARNING .
Примечания
Замечание:
Функция money_format() определена только если в системе присутствует функция strfmon. Например, в Windows она отсутствует, поэтому money_format() не определена в Windows.
Замечание:
На работу этой функции влияет установка категории LC_MONETARY текущей локали. Перед использованием этой функции установите нужную локаль с помощью setlocale() .
Примеры
Пример #1 Пример использования money_format()
Проиллюстрируем применение этой функции для различных локалей и разных описаний формата.
// международный формат в локали en_US
setlocale ( LC_MONETARY , ‘en_US’ );
echo money_format ( ‘%i’ , $number ) . «\n» ;
// USD 1,234.56
// Итальянский национальный формат с 2 знаками после запятой
setlocale ( LC_MONETARY , ‘it_IT’ );
echo money_format ( ‘%.2n’ , $number ) . «\n» ;
// Eu 1.234,56
// Использование отрицательных чисел
$number = — 1234.5672 ;
// национальный формат США, с использованием скобок для
// отрицательных чисел и 10 знаков до запятой
setlocale ( LC_MONETARY , ‘en_US’ );
echo money_format ( ‘%(#10n’ , $number ) . «\n» ;
// ($ 1,234.57)
// подобно предыдущему, но с добавлением 2 знаков после запятой
// и ‘*’ в качестве символа заполнения
echo money_format ( ‘%=*(#10.2n’ , $number ) . «\n» ;
// ($********1,234.57)
// Выравнивание влево, ширина 14 знаков, 8 знаков до запятой,
// 2 знака после запятой, без разбиения на группы
// с использованием международного формата в локали de_DE.
setlocale ( LC_MONETARY , ‘de_DE’ );
echo money_format ( ‘%=*^-14#8.2i’ , 1234.56 ) . «\n» ;
// Eu 1234,56****
// А теперь добавим текст перед и после описанием формата
setlocale ( LC_MONETARY , ‘en_GB’ );
$fmt = ‘Итоговая сумма: %i (после 10%% скидки)’ ;
echo money_format ( $fmt , 1234.56 ) . «\n» ;
// Итоговая сумма: GBP 1,234.56 (после 10% скидки)
Смотрите также
- setlocale() — Устанавливает настройки локали
- sscanf() — Разбирает строку в соответствии с заданным форматом
- sprintf() — Возвращает отформатированную строку
- printf() — Выводит отформатированную строку
- number_format() — Форматирует число с разделением групп