- Регулярные выражения для того, чтобы оставить в строке PHP только цифры
- Наша реальность
- Другие примеры
- ctype_digit
- Описание
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 14 notes
- Как вывести только цифры php
- Как вывести только цифры php
- number_format
- Описание
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- Смотрите также
- User Contributed Notes 38 notes
Регулярные выражения для того, чтобы оставить в строке PHP только цифры
Дата публикации: 2017-03-23
От автора: моя племянница решила стать писателем-фантастом. Это девятилетнее дарование несколько дней пыталась придумать сюжет будущего шедевра, не забывая попутно «пытать» и своих родственников. В результате она нафантазировала мир, в котором вместо букв используются цифры. Тогда в этой мире будут в PHP только цифры?
Наша реальность
Но вернемся в нашу реальность, где цифры – это цифры, а буквами пишут слова. И опять сегодня речь пойдет о регулярных выражениях. Только с их помощью можно правильно просеять содержимое и получить искомую строчку, сочетание символов или просто цифры. Поиском последних и займемся. Но сначала определимся, что мы хотим сделать с найденными цифрами.
С помощью PHP оставляем только цифры:
Бесплатный курс по PHP программированию
Освойте курс и узнайте, как создать динамичный сайт на PHP и MySQL с полного нуля, используя модель MVC
В курсе 39 уроков | 15 часов видео | исходники для каждого урока
Теперь разберемся, что делает функция preg_replace(). Первым аргументом она принимает шаблон, по которому будет происходить поиск значений в строке $str1 (третий аргумент) и затем заменять найденное на второй аргумент (пробел).
Рассмотрим поближе регулярку: /[^0-9]/
В шаблоне указано, что нужно находить все символы, кроме цифр. В свою очередь preg_replace() нашла значения, соответствующие регулярному выражению и заменила на пробел. Таким образом мы реализовали ввод только цифр с помощью PHP.
Другие примеры
«Окунемся» глубже и модифицируем шаблон. Для этого используем в синтаксисе регулярных выражений метасимволы: \d – означает любую цифру, \D – обозначает любой символ, не являющийся цифрой.
Применим эти метасимволы в следующих примерах. В первом из них мы задействуем еще одну функцию PHP, которая предназначена для работы с регулярками.
Источник
ctype_digit
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
ctype_digit — Проверяет наличие цифровых символов в строке
Описание
Проверяет, являются ли все символы в строке text цифровыми.
Список параметров
Если передано целое число ( int ) в диапазоне между -128 и 255 включительно, то оно будет обработано как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.
Возвращаемые значения
Возвращает true , если каждый символ строки text является десятичной цифрой, либо false в противном случае.
Примеры
Пример #1 Пример использования ctype_digit()
Результат выполнения данного примера:
Пример #2 Пример использования ctype_digit() со сравнением строк и целых чисел
= ’42’ ;
$integer = 42 ;
ctype_digit ( $numeric_string ); // true
ctype_digit ( $integer ); // false (ASCII 42 — это символ *)
is_numeric ( $numeric_string ); // true
is_numeric ( $integer ); // true
?>
Смотрите также
- ctype_alnum() — Проверяет наличие буквенно-цифровых символов
- ctype_xdigit() — Проверяет наличие шестнадцатеричных цифр
- is_numeric() — Проверяет, является ли переменная числом или строкой, содержащей число
- is_int() — Проверяет, является ли переменная целым числом
- is_string() — Проверяет, является ли переменная строкой
User Contributed Notes 14 notes
All basic PHP functions which i tried returned unexpected results. I would just like to check whether some variable only contains numbers. For example: when i spread my script to the public i cannot require users to only use numbers as string or as integer. For those situation i wrote my own function which handles all inconveniences of other functions and which is not depending on regular expressions. Some people strongly believe that regular functions slow down your script.
The reason to write this function:
1. is_numeric() accepts values like: +0123.45e6 (but you would expect it would not)
2. is_int() does not accept HTML form fields (like: 123) because they are treated as strings (like: «123»).
3. ctype_digit() excepts all numbers to be strings (like: «123») and does not validate real integers (like: 123).
4. Probably some functions would parse a boolean (like: true or false) as 0 or 1 and validate it in that manner.
My function only accepts numbers regardless whether they are in string or in integer format.
/**
* Check input for existing only of digits (numbers)
* @author Tim Boormans
* @param $digit
* @return bool
*/
function is_digit ( $digit ) <
if( is_int ( $digit )) <
return true ;
> elseif( is_string ( $digit )) <
return ctype_digit ( $digit );
> else <
// booleans, floats and others
return false ;
>
>
?>
Interesting to note that you must pass a STRING to this function, other values won’t be typecasted (I figured it would even though above explicitly says string $text).
= 42 ; //Answer to life
$x = ctype_digit ( $val );
?>
Will return false, even though, when typecasted to string, it would be true.
= ’42’ ;
$x = ctype_digit ( $val );
?>
Returns True.
Could do this too:
= 42 ;
$x = ctype_digit ((string) $val );
?>
Which will also return true, as it should.
ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII ‘0’-‘9’) and false for the rest.
ctype_digit(5) -> false
ctype_digit(48) -> true
ctype_digit(255) -> false
ctype_digit(256) -> true
(Note: the PHP type must be an int; if you pass strings it works as expected)
Источник
Как вывести только цифры php
Здесь могла бы быть ваша реклама
Покинул форум
Сообщений всего: 4574
Дата рег-ции: Июль 2006
Откуда: Israel
Секрет
Теперь, когда вы уже наверняка второпях отправили свой запрос,
я расскажу вам простой секрет, который сэкономит вам уйму ожиданий,
даже если первый ответ по теме последуем сразу же.
Само собой я знаю что ответят мне тут же, и если я посмотрю
на сообщения на форуме, то пойму что в общем то я и не ошибаюсь.
Но еще я точно замечу, что очень мало тем, в которых всего два ответа :
вопрос автора и еще два сообщение вида Ответ + Спасибо
После этого приходится начинать уточнять этим неграмотным что мне надо.
Они что, сами читать не умеют? А уточнять приходится.
И иногда пока они переварят то что я им скажу проходит и не одна ночь..
Уверен что если бы я им сказал что у меня есть
фиолетовый квадрат, и нужно превратить его в синий треугольник
и я пытался взять кисточку, макнуть в банку и поводить ей по квадрату
но почему то кисточка не принимала цвет краски в банке,
то на мой вопрос — где взять правильные банки мне бы ответили гораздо быстрее
предложив её открыть, а не тратить еще стольник на жестянку.
Поэтому с тех пор я строю свои вопросы по проверенной давным давно схеме:
Что есть
Что нужно получить
Как я пытался
Почему или что у меня не получилось.
На последок как оно происходит на форумах
Новичок: Подскажите пожалуста самый крепкий сорт дерева! Весь инет перерыл, поиском пользовался!
Старожил: Объясни, зачем тебе понадобилось дерево? Сейчас оно в строительстве практически не используется.
Новичок: Я небоскрёб собираюсь строить. Хочу узнать, из какого дерева делать перекрытия между этажами!
Старожил: Какое дерево? Ты вообще соображаешь, что говоришь?
Новичок: Чем мне нравиться этот форум — из двух ответов ниодного конкретного. Одни вопросы неподелу!
Старожил: Не нравится — тебя здесь никто не держит. Но если ты не соображаешь, что из дерева небоскрёбы не строят, то лучше бы тебе сначала школу закончить.
Новичок: Не знаите — лучше молчите! У меня дедушка в деревянном доме живёт! У НЕГО НИЧЕГО НЕ ЛОМАЕТСЯ.
Но у него дом из сосны, а я понимаю, что для небоскрёба нужно дерево прочнее! Поэтому и спрашиваю. А от вас нормального ответа недождёшся.
Прохожий: Самое крепкое дерево — дуб. Вот тебе технология вымачивания дуба в солёной воде, она придаёт дубу особую прочность:
Новичок: Спасибо, братан! То что нужно.
Отредактировано модератором: Uchkuma, 26 Апреля, 2011 — 10:21:12
Источник
Как вывести только цифры php
Здесь могла бы быть ваша реклама
Покинул форум
Сообщений всего: 4574
Дата рег-ции: Июль 2006
Откуда: Israel
Секрет
Теперь, когда вы уже наверняка второпях отправили свой запрос,
я расскажу вам простой секрет, который сэкономит вам уйму ожиданий,
даже если первый ответ по теме последуем сразу же.
Само собой я знаю что ответят мне тут же, и если я посмотрю
на сообщения на форуме, то пойму что в общем то я и не ошибаюсь.
Но еще я точно замечу, что очень мало тем, в которых всего два ответа :
вопрос автора и еще два сообщение вида Ответ + Спасибо
После этого приходится начинать уточнять этим неграмотным что мне надо.
Они что, сами читать не умеют? А уточнять приходится.
И иногда пока они переварят то что я им скажу проходит и не одна ночь..
Уверен что если бы я им сказал что у меня есть
фиолетовый квадрат, и нужно превратить его в синий треугольник
и я пытался взять кисточку, макнуть в банку и поводить ей по квадрату
но почему то кисточка не принимала цвет краски в банке,
то на мой вопрос — где взять правильные банки мне бы ответили гораздо быстрее
предложив её открыть, а не тратить еще стольник на жестянку.
Поэтому с тех пор я строю свои вопросы по проверенной давным давно схеме:
Что есть
Что нужно получить
Как я пытался
Почему или что у меня не получилось.
На последок как оно происходит на форумах
Новичок: Подскажите пожалуста самый крепкий сорт дерева! Весь инет перерыл, поиском пользовался!
Старожил: Объясни, зачем тебе понадобилось дерево? Сейчас оно в строительстве практически не используется.
Новичок: Я небоскрёб собираюсь строить. Хочу узнать, из какого дерева делать перекрытия между этажами!
Старожил: Какое дерево? Ты вообще соображаешь, что говоришь?
Новичок: Чем мне нравиться этот форум — из двух ответов ниодного конкретного. Одни вопросы неподелу!
Старожил: Не нравится — тебя здесь никто не держит. Но если ты не соображаешь, что из дерева небоскрёбы не строят, то лучше бы тебе сначала школу закончить.
Новичок: Не знаите — лучше молчите! У меня дедушка в деревянном доме живёт! У НЕГО НИЧЕГО НЕ ЛОМАЕТСЯ.
Но у него дом из сосны, а я понимаю, что для небоскрёба нужно дерево прочнее! Поэтому и спрашиваю. А от вас нормального ответа недождёшся.
Прохожий: Самое крепкое дерево — дуб. Вот тебе технология вымачивания дуба в солёной воде, она придаёт дубу особую прочность:
Новичок: Спасибо, братан! То что нужно.
Отредактировано модератором: Uchkuma, 26 Апреля, 2011 — 10:21:12
Источник
number_format
(PHP 4, PHP 5, PHP 7, PHP 8)
number_format — Форматирует число с разделением групп
Описание
Форматирует число сгруппированными тысячами и, возможно, десятичными цифрами.
Список параметров
Устанавливает число знаков после запятой. Если 0 , decimal_separator опускается в возвращаемом значении.
Устанавливает разделитель дробной части.
Устанавливает разделитель тысяч.
Возвращаемые значения
Отформатированное число num .
Список изменений
Версия | Описание |
---|---|
8.0.0 | До этой версии функция number_format() принимала один, два или четыре параметра (но не три). |
7.2.0 | number_format() была изменена, чтобы не возвращать -0 , ранее -0 могло быть возвращено в случаях, когда num был -0.01 . |
Примеры
Пример #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 38 notes
It’s not explicitly documented; number_format also rounds:
= 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
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
if you want to benchmark all costs for 5 seconds:
( 5 );
for( $cost = 4 ;;++ $cost ) <
$start = microtime ( true );
password_hash ( «test» , PASSWORD_BCRYPT , [ «cost» => $cost ]);
$end = microtime ( true );
echo «cost < $cost >: » .(int)(( $end — $start )* 1000 ). «ms — » . number_format ( $end — $start , 4 ). «s\n» ;
>
?>
on my laptop rolling «Intel Core i7-8565U CPU @ 1.80GHz» it prints:
$ php foo.php
cost 4: 1ms — 0.0010s
cost 5: 2ms — 0.0022s
cost 6: 3ms — 0.0038s
cost 7: 6ms — 0.0069s
cost 8: 14ms — 0.0147s
cost 9: 25ms — 0.0254s
cost 10: 55ms — 0.0554s
cost 11: 103ms — 0.1040s
cost 12: 184ms — 0.1848s
cost 13: 367ms — 0.3676s
cost 14: 737ms — 0.7379s
cost 15: 1881ms — 1.8810s
(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.
function number_format_unlimited_precision ( $number , $decimal = ‘.’ )
<
$broken_number = explode ( $decimal , $number );
return number_format ( $broken_number [ 0 ]). $decimal . $broken_number [ 1 ];
>
?>
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.
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
// formats money to a whole number or with 2 decimals; includes a dollar sign in front
function formatMoney ( $number , $cents = 1 ) < // cents: 0=never, 1=if needed, 2=always
if ( is_numeric ( $number )) < // a number
if (! $number ) < // zero
$money = ( $cents == 2 ? ‘0.00’ : ‘0’ ); // output zero
> else < // value
if ( floor ( $number ) == $number ) < // whole number
$money = number_format ( $number , ( $cents == 2 ? 2 : 0 )); // format
> else < // cents
$money = number_format ( round ( $number , 2 ), ( $cents == 0 ? 0 : 2 )); // format
> // integer or decimal
> // value
return ‘$’ . $money ;
> // numeric
> // formatMoney
$a = array( 1 , 1234 , 1.5 , 1.234 , 2.345 , 2.001 , 2.100 , ‘1.000’ , ‘1.2345’ , ‘12345’ , 0 , ‘0.00’ );
// show cents if needed ($cents=1)
foreach ( $a as $b ) echo ( ‘
‘ . $b . ‘ = ‘ . formatMoney ( $b , 1 ));
1 = $ 1
1234 = $ 1 , 234
1.5 = $ 1.50
1.234 = $ 1.23
2.345 = $ 2.35
2.001 = $ 2.00
2.1 = $ 2.10
1.000 = $ 1
1.2345 = $ 1.23
12345 = $ 12 , 345
0 = $ 0
0.00 = $ 0
// never show cents ($cents=0)
foreach ( $a as $b ) echo ( ‘
‘ . $b . ‘ = ‘ . formatMoney ( $b , 0 ));
1 = $ 1
1234 = $ 1 , 234
1.5 = $ 2
1.234 = $ 1
2.345 = $ 2
2.001 = $ 2
2.1 = $ 2
1.000 = $ 1
1.2345 = $ 1
12345 = $ 12 , 345
0 = $ 0
0.00 = $ 0
// always show cents ($cents=2)
foreach ( $a as $b ) echo ( ‘
‘ . $b . ‘ = ‘ . formatMoney ( $b , 2 ));
1 = $ 1.00
1234 = $ 1 , 234.00
1.5 = $ 1.50
1.234 = $ 1.23
2.345 = $ 2.35
2.001 = $ 2.00
2.1 = $ 2.10
1.000 = $ 1.00
1.2345 = $ 1.23
12345 = $ 12 , 345.00
0 = $ 0.00
0.00 = $ 0.00
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
When apply number_format on number with separator on thousands, result is wrong. This function accept number of any format
function format_price ( $number , $decPlaces , $decSep , $thouSep )<
//$number — number for format
//$decPlaces — number of decimal places
//$decSep — separator for decimals
//$thouSep — separator for thousands
//first remove all white spaces
$number = preg_replace ( ‘/\s+/’ , » , $number );
//split string into array
$numberArr = str_split ( $number );
//reverse array and not preserve key, keys will help to find decimal place
$numberArrRev = array_reverse ( $numberArr );
//find first occurrence of non number character, that will be a decimal place
//store $key into variable $decPointIsHere
foreach ( $numberArrRev as $key => $value ) <
if(! is_numeric ( $value )) <
if( $decPointIsHere == «» ) <
$decPointIsHere = $key ;
>
>
>
//decimal comma or whatever it is replace with dot
//$decPointIsHere is the key of the element that will contain decimal separator dot
if( $decPointIsHere != «» ) <
$numberArrRev [ $decPointIsHere ]= «.» ;
>
//again check through array for non numerical characters but skipping allready processed keys
//if is not number remove from array
//reverse back, at the start reversed array $numberArrRev to $numberArr
$numberArr = array_reverse ( $numberArrRev );
//create string from array
$numberClean = implode ( «» , $numberArr );
// apply php number_format function
return number_format ( $numberClean , $decPlaces , $decSep , $thouSep );
echo format_price ( «1 225 552, 55» , 2 , ‘,’ , ‘ ‘ ). «
» ;
echo format_price ( «1.225.552, 55» , 2 , ‘,’ , ‘ ‘ ). «
» ;
echo format_price ( «1’225’552. 55» , 2 , ‘,’ , ‘ ‘ ). «
» ;
echo format_price ( «1225552.55» , 2 , ‘,’ , ‘ ‘ ). «
» ;
?>
all results are: 1 225 552,55
// Here is a function that produces the same output as number_format() but also works with numbers bigger than 2^53.
function a_number_format($number_in_iso_format, $no_of_decimals=3, $decimals_separator=’.’, $thousands_separator=», $digits_grouping=3) <
// Check input variables
if (!is_numeric($number_in_iso_format)) <
error_log(«Warning! Wrong parameter type supplied in my_number_format() function. Parameter \$number_in_iso_format is not a number.»);
return false;
>
if (!is_numeric($no_of_decimals)) <
error_log(«Warning! Wrong parameter type supplied in my_number_format() function. Parameter \$no_of_decimals is not a number.»);
return false;
>
if (!is_numeric($digits_grouping)) <
error_log(«Warning! Wrong parameter type supplied in my_number_format() function. Parameter \$digits_grouping is not a number.»);
return false;
>
// Prepare variables
$no_of_decimals = $no_of_decimals * 1;
// Explode the string received after DOT sign (this is the ISO separator of decimals)
$aux = explode(«.», $number_in_iso_format);
// Extract decimal and integer parts
$integer_part = $aux[0];
$decimal_part = isset($aux[1]) ? $aux[1] : »;
// Adjust decimal part (increase it, or minimize it)
if ($no_of_decimals > 0) <
// Check actual size of decimal_part
// If its length is smaller than number of decimals, add trailing zeros, otherwise round it
if (strlen($decimal_part) 0) <
$aux = strrev($integer_part);
$integer_part = »;
for ($i=strlen($aux)-1; $i >= 0 ; $i—) <
if ( $i % $digits_grouping == 0 && $i != 0) <
$integer_part .= «<$aux[$i]><$thousands_separator>«;
> else <
$integer_part .= $aux[$i];
>
>
>
$original_number= 9223372036854775805;
echo a_number_format($original_number, 4, ‘.’,»‘»,3);
// Outputs: 9’223’372’036’854’775’805.1230
here is the code to convert number to Indonesian text, this code has limitation as is number_format function. sorry for this.
/*
* Created : Iwan Sapoetra — Jun 13, 2008
* Project : Web
* Package : cgaf
*
*/
function terbilang( $num ,$dec=4) <
$stext = array(
«Nol»,
«Satu»,
«Dua»,
«Tiga»,
«Empat»,
«Lima»,
«Enam»,
«Tujuh»,
«Delapan»,
«Sembilan»,
«Sepuluh»,
«Sebelas»
);
$say = array(
«Ribu»,
«Juta»,
«Milyar»,
«Triliun»,
«Biliun», // remember limitation of float
«—apaan—» ///setelah biliun namanya apa?
);
$w = «»;
if ($num $v) <
if (intval($v)) <
$w.= ‘ ‘.terbilang($v).’ ‘.($i >=0 ? $say[$i] : «»);
>
$i—;
>
>
$w = trim($w);
if ($dec = intval($koma)) <
$w .= » Koma «. terbilang($koma);
>
return trim($w);
>
//example
echo terbilang(999999999999).»\n»;
/**
* result : Sembilan Ratus Sembilan Puluh Sembilan Milyar Sembilan Ratus Sembilan Puluh Sembilan Juta Sembilan Ratus Sembilan Puluh Sembilan Ribu Sembilan Ratus Sembilan Puluh Sembilan
*/
echo terbilang(9999999999999999);
/**
* todo : fix this bug pleasese
* problem : number_format(9999999999999999)
In my function my_number_format() [shown below] there was a bug.
If a negative number which is smaller than 1 was entered (-0. ), then the result was wrongly positive because +0 is equal to -0 (the content of $tmp[0] which was interpretet as numeric value).
Here is the corrected version:
function my_number_format ( $number , $dec_point , $thousands_sep )
<
$was_neg = $number 0 ; // Because +0 == -0
$number = abs ( $number );
$tmp = explode ( ‘.’ , $number );
$out = number_format ( $tmp [ 0 ], 0 , $dec_point , $thousands_sep );
if (isset( $tmp [ 1 ])) $out .= $dec_point . $tmp [ 1 ];
if ( $was_neg ) $out = «- $out » ;
?>
Thanks to Federico Cassinelli for the bug report.
[EDIT BY danbrown AT php DOT net: The original note follows.]
Let’s say we got the number $inp = 1234.56
return number_format ( $inp , 2 , ‘,’ , ‘.’ );
?>
you can get the German format 1.234,56. (Comma as decimal separator and point as thousand separator)
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:
function my_number_format ( $number , $dec_point , $thousands_sep )
<
$tmp = explode ( ‘.’ , $number );
$out = number_format ( $tmp [ 0 ], 0 , $dec_point , $thousands_sep );
if (isset( $tmp [ 1 ])) $out .= $dec_point . $tmp [ 1 ];
A simple funtion to format american dollars.
function formatMoney ( $money ) <
if( $money 1 ) <
$money = ‘¢’ . $money * 100 ;
>
else <
$dollars = intval ( $money );
$cents = $money — $dollars ;
$cents = $cents * 100 ;
$money = ‘$’ . $dollars . ‘ and ¢’ . $cents ;
>
return $money ;
>
echo formatmoney ( ‘52.342’ );
?>
This will output: » $52 and ¢34.2 «.
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!
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’]);
>
hope this helps =)
[]’s
function formats numbers of datetime type,
[ «zaman» ]= «1983-8-28 5:5:5» ;
function _parseDatetimeToList ( $datetimeStr ) < //datetime format: Y-m-d H-i-s
$datetimeArray = explode ( » » , $datetimeStr );
$dateArray = explode ( «-» , $datetimeArray [ 0 ]);
$year = str_pad ( $dateArray [ 0 ], 2 , «0» , STR_PAD_LEFT );
$month = str_pad ( $dateArray [ 1 ], 2 , «0» , STR_PAD_LEFT );
$day = str_pad ( $dateArray [ 2 ], 2 , «0» , STR_PAD_LEFT );
$timeArray = explode ( «:» , $datetimeArray [ 1 ]);
$hour = str_pad ( $timeArray [ 0 ], 2 , «0» , STR_PAD_LEFT );
$minute = str_pad ( $timeArray [ 1 ], 2 , «0» , STR_PAD_LEFT );
$second = str_pad ( $timeArray [ 2 ], 2 , «0» , STR_PAD_LEFT );
return array( $year , $month , $day , $hour , $minute , $second );
>
list( $year , $month , $day , $hour , $minute , $second ) = _parseDatetimeToList ( $_GET [ «zaman» ]); // 1983-1-28 5:5:5
?>
Be carreful, when you’re using French notation
means : number_format(124.25, 2 , ‘,’ , ‘ ‘) with ‘,’ as dec_point,
Don’t forget to specify thousands_sep that default is ‘,’ to another value, otherwise function will return null.
I was looking for a SIMPLE way to format currency and account for negative values while not losing the calculation properties of my number. Here’s my function — it’s not rocket science, but maybe can help someone along the way.
function wims_currency ( $number ) <
if ( $number 0 ) <
$print_number = «($ » . str_replace ( ‘-‘ , » , number_format ( $number , 2 , «.» , «,» )) . «)» ;
> else <
$print_number = «$ » . number_format ( $number , 2 , «.» , «,» ) ;
>
return $print_number ;
>
?>
Sample use:
= ( $pur_po_total + $pur_item_total );
$print_pur_po_total = wims_currency ( $pur_po_total );
?>
Returns (for example) $ 44,561.00 or, if a negative ($ 407,250.00)
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.
function bytes ( $a ) <
$unim = array( «B» , «KB» , «MB» , «GB» , «TB» , «PB» );
$c = 0 ;
while ( $a >= 1024 ) <
$c ++;
$a = $a / 1024 ;
>
return number_format ( $a ,( $c ? 2 : 0 ), «,» , «.» ). » » . $unim [ $c ];
>
?>
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 no, how about the following function? (I fixed somethings like bugs of the function in the old comment.)
function number_format_unchanged_precision ( $number , $dec_point = ‘.’ , $thousands_sep = ‘,’ ) <
if( $dec_point == $thousands_sep ) <
trigger_error ( ‘2 parameters for ‘ . __METHOD__ . ‘() have the same value, that is «‘ . $dec_point . ‘» for $dec_point and $thousands_sep’ , E_USER_WARNING );
// It corresponds «PHP Warning: Wrong parameter count for number_format()», which occurs when you use $dec_point without $thousands_sep to number_format().
>
if( preg_match ( ‘<\.\d+>‘ , $number , $matches )=== 1 ) <
$decimals = strlen ( $matches [ 0 ]) — 1 ;
>else <
$decimals = 0 ;
>
return number_format ( $number , $decimals , $dec_point , $thousands_sep );
>
var_dump ( number_format_unchanged_precision ( 1234.5678 , ‘,’ , ‘.’ ));
var_dump ( number_format_unchanged_precision ( 1234.5678 , ‘,’ ));
var_dump ( number_format_unchanged_precision ( 12345678 ));
var_dump ( number_format_unchanged_precision (- 0.5678 , ‘,’ , ‘.’ )); // It occurred a bug with the function in the old comment.
?>
output is:
string(10) «1.234,5678»
PHP Warning: 2 parameters for number_format_unchanged_precision() have the same value, that is «,» for $dec_point and $thousands_sep in.
string(10) «1,234,5678»
string(10) «12,345,678»
string(7) «-0,5678»
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 numberfix($number)
<
$number = number_format($number,0,»,»,» «);
return str_replace(» «, » «, $number);
>
For use in:
echo $number ; ?> |
function to convert numbers to words
indian: thousand,lakh,crore
Note: function can only convert nos upto 99 crores
= array( ‘0’ => » , ‘1’ => ‘one’ , ‘2’ => ‘two’ , ‘3’ => ‘three’ , ‘4’ => ‘four’ , ‘5’ => ‘five’ , ‘6’ => ‘six’ , ‘7’ => ‘seven’ , ‘8’ => ‘eight’ , ‘9’ => ‘nine’ , ’10’ => ‘ten’ , ’11’ => ‘eleven’ , ’12’ => ‘twelve’ , ’13’ => ‘thirteen’ , ’14’ => ‘fouteen’ , ’15’ => ‘fifteen’ , ’16’ => ‘sixteen’ , ’17’ => ‘seventeen’ , ’18’ => ‘eighteen’ , ’19’ => ‘nineteen’ , ’20’ => ‘twenty’ , ’30’ => ‘thirty’ , ’40’ => ‘fourty’ , ’50’ => ‘fifty’ , ’60’ => ‘sixty’ , ’70’ => ‘seventy’ , ’80’ => ‘eighty’ , ’90’ => ‘ninty’ , ‘100’ => ‘hundred &’ , ‘1000’ => ‘thousand’ , ‘100000’ => ‘lakh’ , ‘10000000’ => ‘crore’ );
function no_to_words ( $no )
< global $words ;
if( $no == 0 )
return ‘ ‘ ;
else < $novalue = '' ; $highno = $no ; $remainno = 0 ; $value = 100 ; $value1 = 1000 ;
while( $no >= 100 ) <
if(( $value $no ) &&( $no $value1 )) <
$novalue = $words [ » $value » ];
$highno = (int)( $no / $value );
$remainno = $no % $value ;
break;
>
$value = $value1 ;
$value1 = $value * 100 ;
>
if( array_key_exists ( » $highno » , $words ))
return $words [ » $highno » ]. » » . $novalue . » » . no_to_words ( $remainno );
else <
$unit = $highno % 10 ;
$ten =(int)( $highno / 10 )* 10 ;
return $words [ » $ten » ]. » » . $words [ » $unit » ]. » » . $novalue . » » . no_to_words ( $remainno );
>
>
>
echo no_to_words ( 999978987 );
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.
function ordinal ( $num )
<
// Special case «teenth»
if ( ( $num / 10 ) % 10 != 1 )
<
// Handle 1st, 2nd, 3rd
switch( $num % 10 )
<
case 1 : return $num . ‘st’ ;
case 2 : return $num . ‘nd’ ;
case 3 : return $num . ‘rd’ ;
>
>
// Everything else is «nth»
return $num . ‘th’ ;
>
?>
This is a simple and useful function to convert a byte number in a KB or MB:
=1048576) <
$numero=number_format($bytes/1048576, 2, ‘,’, ‘.’).» MByte»;
return $numero;
>
>
?>
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,».»,»,») .»,-«;
>
if you want as a separator and use windows charset this piece of code may help:
= number_format ( $number , 2 , ‘.’ , chr ( 0xA0 ));
?>
function convertNumberToWordsForIndia ( $number ) <
//A function to convert numbers into Indian readable words with Cores, Lakhs and Thousands.
$words = array(
‘0’ => » , ‘1’ => ‘one’ , ‘2’ => ‘two’ , ‘3’ => ‘three’ , ‘4’ => ‘four’ , ‘5’ => ‘five’ ,
‘6’ => ‘six’ , ‘7’ => ‘seven’ , ‘8’ => ‘eight’ , ‘9’ => ‘nine’ , ’10’ => ‘ten’ ,
’11’ => ‘eleven’ , ’12’ => ‘twelve’ , ’13’ => ‘thirteen’ , ’14’ => ‘fouteen’ , ’15’ => ‘fifteen’ ,
’16’ => ‘sixteen’ , ’17’ => ‘seventeen’ , ’18’ => ‘eighteen’ , ’19’ => ‘nineteen’ , ’20’ => ‘twenty’ ,
’30’ => ‘thirty’ , ’40’ => ‘fourty’ , ’50’ => ‘fifty’ , ’60’ => ‘sixty’ , ’70’ => ‘seventy’ ,
’80’ => ‘eighty’ , ’90’ => ‘ninty’ );
//First find the length of the number
$number_length = strlen ( $number );
//Initialize an empty array
$number_array = array( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 );
$received_number_array = array();
//Store all received numbers into an array
for( $i = 0 ; $i $number_length ; $i ++)
//Populate the empty array with the numbers received — most critical operation
for( $i = 9 — $number_length , $j = 0 ; $i 9 ; $i ++, $j ++)< $number_array [ $i ] = $received_number_array [ $j ]; >
$number_to_words_string = «» ;
//Finding out whether it is teen ? and then multiplying by 10, example 17 is seventeen, so if 1 is preceeded with 7 multiply 1 by 10 and add 7 to it.
for( $i = 0 , $j = 1 ; $i 9 ; $i ++, $j ++) <
if( $i == 0 || $i == 2 || $i == 4 || $i == 7 ) <
if( $number_array [ $i ]== «1» ) <
$number_array [ $j ] = 10 + $number_array [ $j ];
$number_array [ $i ] = 0 ;
>
>
>
echo convertNumberToWordsForIndia ( «987654321» );
//Output ==> Indian Rupees Ninty Eight Crores Seventy Six Lakhs Fifty Four Thousand Three Hundred & Twenty One Only.
?>
= 1234567.896 ;
echo ‘1: ‘ . number_format ( $number , 2 , ‘,’ , » ). ‘
‘ ;
echo ‘2: ‘ . number_format ( $number , 2 , ‘.’ , » ). ‘
‘ ;
echo ‘3: ‘ . number_format ( $number , 2 , ‘,’ , ‘.’ ). ‘
‘ ;
echo ‘4: ‘ . number_format ( $number , 2 , ‘.’ , ‘,’ ). ‘
‘ ;
echo ‘5: ‘ . number_format ( $number , 2 , ‘,’ , ‘ ‘ ). ‘
‘ ;
echo ‘6: ‘ . number_format ( $number , 2 , ‘,’ , «‘» ). ‘
‘ ;
echo ‘7: ‘ . number_format ( $number , 2 , » , » ). ‘
‘ ;
?>
Resultado: Result:
1: 1234567,90 -> Decimal separado por ,
2: 1234567.90 -> Decimal separado por .
3: 1.234.567,90 -> Moeda Brasil, Alemanha
4: 1,234,567.90 -> Inglês, USA
5: 1 234 567,90 -> França
6: 1’234’567,90 -> Suíça
7: 123456790 -> Sem decimal
This function is used for reformatting already formatted numbers.
function formatNumber ( $number , $format =[], $oldDecimalSeparator = «,.·'» , $multiplier = 1 )
<
/**
$format — the array of formatting options, details in the example.
$oldDecimalSeparator — decimal separator used in the $number. If the separator can meet different characters, then you need to record them all, for example: ‘,.’.
$multiplier — typically used to adjust prices up or down.
*/
if ( $format ) <
$format += [ ‘numOfDecimals’ => 0 , ‘decimalSeparator’ => ‘.’ , ‘thousandSeparator’ => » ]; # Default format
# Find decimal separator
# The decimal separator is the one that is the last and does not occur more than once
if ( $letters = str_replace ( ‘ ‘ , » , $number )) < # Replace spaces
if ( $letters = preg_replace ( ‘/^-/’ , » , $letters )) < # Remove minus
if ( $letters = preg_replace ( ‘/9/’ , » , $letters )) < # Get all non digits
$lastletter = substr ( $letters , — 1 ); # Returns last char
if ( substr_count ( $letters , $lastletter ) == 1 ) <
if ( strpos ( $oldDecimalSeparator , $lastletter ) !== false )
$oldDecimalSep = $lastletter ;
else
return $number ;
>
>
>
>
$number = preg_replace ( ‘/[^0-9-]/’ , » , $number ); # Remove all non digits except ‘minus’
if ( $oldDecimalSep )
$number = str_replace ( $oldDecimalSep , ‘.’ , $number ); # Format to float
if ( $multiplier != 1 )
$number = $number * $multiplier ;
# Convert float to new format
$number = number_format ( $number ,
$format [ ‘numOfDecimals’ ],
$format [ ‘decimalSeparator’ ],
$format [ ‘thousandSeparator’ ]
);
>
return $number ;
>
/**
Example. Formatting data in which the decimal separator can occur as the comma and dot. Formatting into Russian format: -12 345,67
*/
echo formatNumber ( $number , [
‘numOfDecimals’ => 2 ,
‘decimalSeparator’ => ‘,’ ,
‘thousandSeparator’ => ‘ ‘
], ‘,.’ );
Источник