Php number format integer

number_format

Функция принимает один, два или четыре аргумента (не три):

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

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

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

Список параметров

Устанавливает число знаков после запятой.

Устанавливает разделитель дробной части.

Устанавливает разделитель тысяч.

Возвращаемые значения

Возвращается отформатированное число number .

Список изменений

Версия Описание
5.4.0 Функция поддерживает многобайтную строку в качестве параметров dec_point и thousands_sep . В предыдущих версиях в качестве разделителя использовался только первый байт из каждого параметра.

Примеры

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

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

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

// французский формат
$nombre_format_francais = number_format ( $number , 2 , ‘,’ , ‘ ‘ );
// 1 234,56

// английский формат без разделителей групп
$english_format_number = number_format ( $number , 2 , ‘.’ , » );
// 1234.57

Смотрите также

  • money_format() — Форматирует число как денежную величину
  • sprintf() — Возвращает отформатированную строку
  • printf() — Выводит отформатированную строку
  • sscanf() — Разбирает строку в соответствии с заданным форматом

Источник

number_format

Форматирует число сгруппированными тысячными и, возможно, десятичными цифрами, используя математическое правило округления.

Список параметров

Устанавливает число знаков после запятой. Если 0 , decimal_separator опускается в возвращаемом значении.

Устанавливает разделитель дробной части.

Устанавливает разделитель тысяч.

Возвращаемые значения

Отформатированное число num .

Список изменений

Версия Описание
8.0.0 До этой версии функция number_format() принимала один, два или четыре параметра (но не три).
7.2.0 number_format() была изменена, чтобы не возвращать -0 , ранее -0 могло быть возвращено в случаях, когда num был -0.01 .
Читайте также:  Java for oracle sql developer

Примеры

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

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

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

// французский формат
$nombre_format_francais = number_format ( $number , 2 , ‘,’ , ‘ ‘ );
// 1 234,56

// английский формат без разделителей групп
$english_format_number = number_format ( $number , 2 , ‘.’ , » );
// 1234.57

Смотрите также

  • money_format() — Форматирует число как денежную величину
  • sprintf() — Возвращает отформатированную строку
  • printf() — Выводит отформатированную строку
  • sscanf() — Разбирает строку в соответствии с заданным форматом

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’ ;

Читайте также:  Java throw exception logging

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 );
>

Читайте также:  Vue typescript props type

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!

Источник

PHP number_format() Function

The number_format() function formats a number with grouped thousands.

Note: This function supports one, two, or four parameters (not three).

Syntax

Parameter Values

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»

Technical Details

Return Value: Returns the formatted number
PHP Version: 4+
Changelog: As of PHP 5.4, this function supports multiple bytes in the parameters decimalpoint and separator. Only the first byte of each separator was used in older versions.

More Examples

Example

You want to return a price: One parameter will round the number (it will be formatted without decimals). Two parameters should give the result you want:

$num = 1999.9;
$formattedNum = number_format($num).»
«;
echo $formattedNum;
$formattedNum = number_format($num, 2);
echo $formattedNum;
?>

Источник

Оцените статью