php разделить тысячи пробелом
Php разделить тысячи пробелом
В этом разделе помещены уроки по PHP скриптам, которые Вы сможете использовать на своих ресурсах.
Фильтрация данных с помощью zend-filter
Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.
Контекстное экранирование с помощью zend-escaper
Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.
Подключение Zend модулей к Expressive
Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.
Совет: отправка информации в Google Analytics через API
Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.
Подборка PHP песочниц
Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.
Совет: активация отображения всех ошибок в PHP
При поднятии PHP проекта на новом рабочем окружении могут возникнуть ошибки отображение которых изначально скрыто базовыми настройками. Это можно исправить, прописав несколько команд.
Агент
PHP парсер юзер агента с поддержкой Laravel, работающий на базе библиотеки Mobile Detect.
Как разбить число на разряды (тысячи, миллионы и т.д.)?
Фото. Лайки. При достижении 1 000 или 10 000 лайков, цифры выводятся таким образом:
Интересует, как разделять тысячные, миллионные и т.п значения, чтобы например, было так
Возможно, в PHP есть стандартная функция, которая этим занимается?
6 ответов 6
Внезапно, для форматирования чисел используется number_format.
number
Форматируемое число.
decimals
Устанавливает число знаков после запятой.
dec_point
Устанавливает разделитель дробной части.
thousands_sep
Устанавливает разделитель тысяч.
number_format() — Форматирует число с разделением групп
$str = 10000; number_format($str, 0, ‘.’, ‘ ‘);
Всё ещё ищете ответ? Посмотрите другие вопросы с метками php или задайте свой вопрос.
Связанные
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.9.17.40238
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
number_format
(PHP 4, PHP 5, PHP 7, PHP 8)
number_format — Форматирует число с разделением групп
Описание
Форматирует число сгруппированными тысячами и, возможно, десятичными цифрами.
Список параметров
Устанавливает разделитель дробной части.
Устанавливает разделитель тысяч.
Возвращаемые значения
Список изменений
Примеры
Пример #1 Пример использования number_format()
Во Франции обычно используются 2 знака после запятой (‘,’), и пробел (‘ ‘) в качестве разделителя групп. Этот пример демонстрирует различные способы форматирования чисел:
Смотрите также
User Contributed Notes 38 notes
It’s not explicitly documented; number_format also rounds:
Outputs a human readable number.
if you want to benchmark all costs for 5 seconds:
(with ms meaning milliseconds and s meaning seconds)
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.
You can change %03d to %04d, etc.
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.
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.
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
//again check through array for non numerical characters but skipping allready processed keys
//if is not number remove from array
// 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
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:
A simple funtion to format american dollars.
To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people below):
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];
>;
>;
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» ;
Don’t forget to specify thousands_sep that default is ‘,’ to another value, otherwise function will return null.
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.
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
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.
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 is a simple and useful function to convert a byte number in a KB or MB:
if you want as a separator and use windows charset this piece of code may help:
echo convertNumberToWordsForIndia ( «987654321» );
//Output ==> Indian Rupees Ninty Eight Crores Seventy Six Lakhs Fifty Four Thousand Three Hundred & Twenty One Only.
?>
Форум PHP программистов ► PHP основы ► Счетчики, дата, время, арифметические операции
Новичок
Профиль
Группа: Пользователь
Сообщений: 11
Пользователь №: 16371
На форуме:
Карма:
Приветствую!
Помогите, пожалуйста, разобраться как в Числе отделить пробелом тысячи, миллионы.
Например: Число хранится в виде: 4000000, а вывести его надо так: 4 000 000
Нашел функцию:
string chunk_split ( string body [, int chunklen [, string end]] )
Функция используется для разбиения строки на фрагменты, например, для приведения результата функции base64_encode() в соответствие с требованиями RFC 2045. Она вставляет строку end (по умолчанию «\r\n») после каждых chunklen символов (по умолчанию 76). Возвращает преобразованную строку без изменения исходной.
НО ОНА разбивает число с начала строки, а не с конца. Получается 400 000 0
money_format
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
money_format — Форматирует число как денежную величину
Эта функция УСТАРЕЛА, начиная с PHP 7.4.0 и была УДАЛЕНА, начиная с PHP 8.0.0. Использовать эту функцию крайне не рекомендуется.
Описание
money_format() форматирует число number как денежную величину. Эта функция вызывает функцию strfmon() языка C, но позволяет преобразовать только одно число за один вызов.
Список параметров
Описание формата состоит из:
необязательной ширины поля
необязательной точности до запятой
необязательной точности после запятой
обязательного описателя преобразования
Флаги
Могут быть использованы следующие флаги: = f
Отключает группировку символов (определяемую текущей локалью).
Подавляет вывод символа валюты.
Если этот флаг задан, поля будут выравнены влево (с отбивкой вправо), вместо используемого по умолчанию выравнивания вправо (с отбивкой влево).
Ширина поля
Точность до запятой
Для обеспечения выравнивания, все символы, выводимые до или после числа, такие как символ валюты или знак, будут дополнены пробелами до одинаковой ширины.
Точность после запятой
Точка, за которой следует число знаков ( p ), выводимых после запятой. Если значение p равно нулю, десятичная точка и цифры после неё не будут выводиться. Если этот параметр отсутствует, число знаков после запятой определяется текущей локалью. Перед форматированием число округляется до указанного количества знаков.
Описатель преобразования
Используется международный денежный формат из текущей локали (например, для американской локали: USD 1,234.56).
Используется национальный денежный формат из текущей локали (например, для локали de_DE: EU1.234,56).
Возвращаемые значения
Список изменений
Примеры
Пример #1 Пример использования money_format()
Проиллюстрируем применение этой функции для различных локалей и разных описаний формата.
Примечания
Функция money_format() определена только если в системе присутствует функция strfmon. Например, в Windows она отсутствует, поэтому money_format() не определена в Windows.
Смотрите также
User Contributed Notes 15 notes
For most of us in the US, we don’t want to see a «USD» for our currency symbol, so ‘%i’ doesn’t cut it. Here’s what I used that worked to get what most people expect to see for a number format.
That gives me a dollar sign at the beginning, and 2 digits at the end.
This is a some function posted before, however various bugs were corrected.
Thank you to Stuart Roe by reporting the bug on printing signals.
/*
That it is an implementation of the function money_format for the
platforms that do not it bear.
The function accepts to same string of format accepts for the
original function of the PHP.
(Sorry. my writing in English is very bad)
‘.’,
‘thousands_sep’ => »,
‘int_curr_symbol’ => ‘EUR’,
‘currency_symbol’ => ‘€’,
‘mon_decimal_point’ => ‘,’,
‘mon_thousands_sep’ => ‘.’,
‘positive_sign’ => »,
‘negative_sign’ => ‘-‘,
‘int_frac_digits’ => 2,
‘frac_digits’ => 2,
‘p_cs_precedes’ => 0,
‘p_sep_by_space’ => 1,
‘p_sign_posn’ => 1,
‘n_sign_posn’ => 1,
‘grouping’ => array(),
‘mon_grouping’ => array(0 => 3, 1 => 3)
This was frustrating me for a while. Debian has a list of valid locales at /usr/share/i18n/SUPPORTED; find yours there if it’s not working properly.
- php разделить текст на первый абзац и остальное
- php разделить число пробелами