number_format
number_format — Форматирует число с разделением групп
Описание
Функция принимает один, два или четыре аргумента (не три):
Если передан только один аргумент, number будет отформатирован без дробной части, но с запятой («,») между каждыми тремя цифрами.
Если переданы два аргумента, number будет отформатирован с decimals знаками после точки («.») и с запятой («,») между каждыми тремя цифрами.
Список параметров
Устанавливает число знаков после запятой.
Устанавливает разделитель дробной части.
Устанавливает разделитель тысяч.
Возвращаемые значения
Список изменений
Примеры
Пример #1 Пример использования number_format()
Во Франции обычно используются 2 знака после запятой (‘,’), и пробел (‘ ‘) в качестве разделителя групп. Этот пример демонстрирует различные способы форматирования чисел:
Смотрите также
User Contributed Notes 38 notes
It’s not explicitly documented; number_format also rounds:
Outputs a human readable number.
Simple function to show money as only dollars if no cents, but will show 2 decimals if cents exist.
The ‘cents’ flag can force to never or always show 2 decimals
And remember to always contribute custom functions if they might be useful to the rest of us or future versions of the php language.
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.
In my function my_number_format() [shown below] there was a bug.
Here is the corrected version:
?>
Thanks to Federico Cassinelli for the bug report.
[EDIT BY danbrown AT php DOT net: The original note follows.]
But I have a problem with that: I want to add commas as thousand separators and change the decimal-separator (this could also be done with str_replace), but I do not want to change the amount of fractional digits!
But since the 2nd argument of number_format is necessary to enter the 3rd and 4th argument, this cannot be done with number_format. You have to change the fractional digits with this function.
But I want that 1234.56 changes into 1.234,56 and 1234.567890123456 changes into 1.234,567890123456
So, I created following function, that doesn’t change the amount of fractional digits:
// Here is a function that produces the same output as number_format() but also works with numbers bigger than 2^53.
$original_number= 9223372036854775805;
echo a_number_format($original_number, 4, ‘.’,»‘»,3);
// Outputs: 9’223’372’036’854’775’805.1230
Just an observation:
The number_format rounds the value of the variable.
$val1 = 1.233;
$val2 = 1.235;
$val3 = 1.237;
echo number_format($val1,2,»,»,».»); // returns: 1,23
echo number_format($val2,2,»,»,».»); // returns: 1,24
echo number_format($val3,2,»,»,».»); // returns: 1,24
Don’t forget to specify thousands_sep that default is ‘,’ to another value, otherwise function will return null.
To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people below):
I’d like to comment to the old notes of «stm555» and «woodynadobhar».
They wrote about «number_format_unlimited_precision()».
I guess many of us need that kind of function, which is the almost same function as number_format but don’t round a number.
Does Anyone know any new solution in a recent PHP version?
If you use space as a separator, it will break on that space in HTML tables.
Furthermore, number_format doesn’t like ‘ ‘ as a fourth parameter. I wrote the following function to display the numbers in an HTML table.
simpler function to convert a number in bytes, kilobytes.
?>
you may also add others units over PeraBytes when the hard disks will reach 1024 PB 🙂
If you want a number of digits after the point, but not unnecessary zeros.
Eg.
number_format(1.20000,4) = 1.2000
num_format(1.20000,4,0) = 1.2
number_format(1.20000,4) = 1.2000
num_format(1.20000,4,2) = 1.20
number_format(1.23456,4) = 1.2345
num_format(1.23456,4,2) = 1.2345
if you want to benchmark all costs for 5 seconds:
(with ms meaning milliseconds and s meaning seconds)
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’]);
>
function formats numbers of datetime type,
[ «zaman» ]= «1983-8-28 5:5:5» ;
function to convert numbers to words
indian: thousand,lakh,crore
Note: function can only convert nos upto 99 crores
I’m not sure if this is the right place anyway, but «ben at last dot fm»‘s ordinal function can be simplified further by removing the redundant «floor» (the result of floor is still a float, it’s the «%» that’s converting to int) and outer switch.
Note that this version also returns the number with the suffix on the end, not just the suffix.
This way, I use my 1st variable for calculations and my 2nd variable for output. I’m sure there are better ways to do it, but this got me back on track.
A simple funtion to format american dollars.
This is a simple and useful function to convert a byte number in a KB or MB:
See also the documentation for localeconv, which will provide values for decimal point and thousands separator from the C standard library.
Of course localeconv features many more locale information, like indicating to put the negative sign behind the value for some locale settings which can’t be used to customize present number_format.
What do you do if some of your numbers have decimal places, and some don’t? You can switch between functions, but if you’re building it in a loop, that’s not a good solution. Instead, we have the same as below, with a slight change:
function number_format_unlimited_precision($number,$decimal = ‘.’) <
$broken_number = explode($decimal,$number);
if($broken_number[1]==0) <
return number_format($broken_number[0]);
>else <
return number_format($broken_number[0]).$decimal.$broken_number[1];
>;
>;
if you want as a separator and use windows charset this piece of code may help:
//again check through array for non numerical characters but skipping allready processed keys
//if is not number remove from array
echo convertNumberToWordsForIndia ( «987654321» );
//Output ==> Indian Rupees Ninty Eight Crores Seventy Six Lakhs Fifty Four Thousand Three Hundred & Twenty One Only.
?>
strval
strval — Возвращает строковое значение переменной
Описание
Возвращает строковое значение переменной. См. документацию по типу string для более подробной информации о преобразовании в строку.
Список параметров
Переменная, которую необходимо преобразовать в строку.
var может быть любого скалярного типа или объектом, который реализует метод __toString(). strval() нельзя применить к массиву или объекту, которые не реализуют метод __toString().
Возвращаемые значения
Примеры
Пример #1 Пример использования strval() с магическим методом PHP 5 __toString().
class StrValTest
<
public function __toString ()
<
return __CLASS__ ;
>
>
// Выводит ‘StrValTest’
echo strval (new StrValTest );
?>
Смотрите также
User Contributed Notes 8 notes
Some notes about how this function has changed over time, with regards the following statement:
> You cannot use strval() on arrays or on objects that
> do not implement the __toString() method.
In PHP 5.3 and below, strval(array(1, 2, 3)) would return the string «Array» without any sort of error occurring.
From 5.4 and above, the return value is unchanged but you will now get a notice-level error: «Array to string conversion».
For objects that do not implement __toString(), the behaviour has varied:
PHP 4: «Object»
PHP 5 = 5.2: Catchable fatal error: Object of class X could not be converted to string
Note on use of fmod()
I used the floating point fmod() in preference to the % operator, because % converts the operands to int, corrupting values outside of the range [-2147483648, 2147483647]
I haven’t bothered with «billion» because the word means 10e9 or 10e12 depending who you ask.
The function returns ‘#’ if the argument does not represent a whole number.
The only way to convert a large float to a string is to use printf(‘%0.0f’,$float); instead of strval($float); (php 5.1.4).
// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015
// full conversion
printf(‘%0.0f’,pow(2,50)); // 112589906846624
echo sprintf(‘%0.0f’,pow(2,50)); // 112589906846624
I can’t help being surprised that
evaluates to true. It’s the same with strval and single quotes.
=== avoids it.
Why does it matter? One of my suppliers, unbelievably, uses 0 to mean standard discount and 0.00 to mean no discount in their stock files.
It seems that one is being treated as an unsigned large int (32 bit), and the other as a signed large int (which has rolled over/under).
As of PHP 5.1.4 (I have not tested it in later versions), the strval function does not attempt to invoke the __toString method when it encounters an object. This simple wrapper function will handle this circumstance for you:
__toString());
else
return strval($value);
>
In complement to Tom Nicholson’s contribution, here is the french version (actually it’s possible to change the language, but you should check the syntax 😉 )
Перевод числа в слова php
Синтаксис
Целые числа ( int ) могут быть указаны в десятичной (основание 10), шестнадцатеричной (основание 16), восьмеричной (основание 8) или двоичной (основание 2) системе счисления. Для задания отрицательных целых ( int ) используется оператор отрицания
Начиная с PHP 7.4.0, целочисленные литералы могут содержать подчеркивания ( _ ) между цифрами для лучшей читаемости литералов. Эти подчеркивания удаляются сканером PHP.
Пример #1 Целые числа
Формально структура целых чисел ( int ) соответствует PHP 7.4.0 (ранее подчеркивания не допускались):
Переполнение целых чисел
Пример #2 Переполнение целых на 32-битных системах
Пример #3 Переполнение целых на 64-битных системах
Преобразование в целое
Из булевого типа
Из чисел с плавающей точкой
Если число с плавающей точкой превышает размеры int (обычно +/- 2.15e+9 = 2^31 на 32-битных системах и +/- 9.22e+18 = 2^63 на 64-битных системах, результат будет неопределенным, так как float не имеет достаточной точности, чтобы вернуть верный результат в виде целого числа ( int ). В этом случае не будет выведено ни предупреждения, ни даже замечания!
Значения NaN и Infinity при приведении к int становятся равными нулю, вместо неопределенного значения в зависимости от платформы.
Из строк
Из NULL
Значение NULL всегда преобразуется в ноль ( 0 ).
Из других типов
Для других типов поведение преобразования в int не определено. Не полагайтесь на любое наблюдаемое поведение, так как оно может измениться без предупреждения.
User Contributed Notes 25 notes
Here are some tricks to convert from a «dotted» IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it’s stored as a BIGINT rather than in characters.
var_dump((int) «010»); //output 10
Casting to an integer using (int) will always cast to the default base, which is 10.
Casting a string to a number this way does not take into account the many ways of formatting an integer value in PHP (leading zero for base 8, leading «0x» for base 16, leading «0b» for base 2). It will simply look at the first characters in a string and convert them to a base 10 integer. Leading zeroes will be stripped off because they have no meaning in numerical values, so you will end up with the decimal value 10 for (int)»010″.
Converting an integer value between bases using (int)010 will take into account the various ways of formatting an integer. A leading zero like in 010 means the number is in octal notation, using (int)010 will convert it to the decimal value 8 in base 10.
This is similar to how you use 0x10 to write in hexadecimal (base 16) notation. Using (int)0x10 will convert that to the base 10 decimal value 16, whereas using (int)»0x10″ will end up with the decimal value 0: since the «x» is not a numerical value, anything after that will be ignored.
If you want to interpret the string «010» as an octal value, you need to instruct PHP to do so. intval(«010», 8) will interpret the number in base 8 instead of the default base 10, and you will end up with the decimal value 8. You could also use octdec(«010») to convert the octal string to the decimal value 8. Another option is to use base_convert(«010», 8, 10) to explicitly convert the number «010» from base 8 to base 10, however this function will return the string «8» instead of the integer 8.
Casting a string to an integer follows the same the logic used by the intval function:
Returns the integer value of var, using the specified base for the conversion (the default is base 10).
intval allows specifying a different base as the second argument, whereas a straight cast operation does not, so using (int) will always treat a string as being in base 10.
php > var_export((int) «010»);
10
php > var_export(intval(«010»));
10
php > var_export(intval(«010», 8));
8
