Функция PHP number_format()
Пример
Формат чисел:
<?php
echo number_format("1000000")."<br>";
echo number_format("1000000",2)."<br>";
echo number_format("1000000",2,",",".");
?>
Определение и использование
Функция number_format() форматирует число с группировкой тысяч.
Примечание. Эта функция поддерживает один, два или четыре параметра (не три).
Синтаксис
number_format(number,decimals,decimalpoint,separator)
Значения параметров
Parameter | Description |
---|---|
number | Required. The number to be formatted. If no other parameters are set, the number will be formatted without decimals and with comma (,) as the thousands separator. |
decimals | Optional. Specifies how many decimals. If this parameter is set, the number will be formatted with a dot (.) as decimal point |
decimalpoint | Optional. Specifies what string to use for decimal point |
separator | Optional. Specifies what string to use for thousands separator. Only the first character of separator is used. For example, "xxx" will give the same output as "x" Note: If this parameter is given, all other parameters are required as well |
Технические детали
Возвращаемое значение: | Возвращает отформатированное число |
---|---|
Версия PHP: | 4+ |
Список изменений: | Начиная с PHP 5.4, эта функция поддерживает несколько байтов в параметрах decimalpoint и separator . В старых версиях использовался только первый байт каждого разделителя. |
Дополнительные примеры
Пример
Вы хотите вернуть цену: Один параметр будет округлять число (оно будет отформатировано без десятичных знаков). Два параметра должны дать желаемый результат:
<?php
$num = 1999.9;
$formattedNum = number_format($num)."<br>";
echo $formattedNum;
$formattedNum = number_format($num, 2);
echo $formattedNum;
?>
❮ Справочник по строкам PHP