Компьютерный журнал
1 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд

Html format number


(PHP 4, PHP 5, PHP 7)

number_format — Форматирует число с разделением групп


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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

User Contributed Notes 36 notes

It’s not explicitly documented; number_format also rounds:

Outputs a human readable number.

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

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.

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(
$say = array(
«Biliun», // remember limitation of float
«—apaan—» ///setelah biliun namanya apa?
$w = «»;

if ($num $v) <
if (intval($v)) <
$w.= ‘ ‘.terbilang($v).’ ‘.($i >=0 ? $say[$i] : «»);
$w = trim($w);
if ($dec = intval($koma)) <
$w .= » Koma «. terbilang($koma);
return trim($w);
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)

// 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

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

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»

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

Читать еще:  Php объявление констант

Here is the corrected version:

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

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:

Html format number

Образец форматирования в XSLT определяется точно так же, как в классе DecimalFormat языка Java. Для того чтобы читателю, не знакомому с Java, не пришлось изучать документацию этого языка, мы приведем полный синтаксис образцов форматирования. Продукции образца форматирования мы будем помечать номерами с префиксом NF, чтобы не путать их с другими продукциями.

Прежде всего, образец форматирования может состоять из двух частей: первая часть определяет форматирование положительного числа, вторая часть — отрицательного. Запишем это в виде EBNF-продукции:

Двум частям образца форматирования соответствуют нетерминалы NFSubpattern , которые разделены нетерминалом NFSubpatternDelim .

В случае если вторая часть образца форматирования опущена, отрицательные числа форматируются точно так же, как и положительные, но им предшествует префикс отрицательного числа (по умолчанию — знак «минус», » — «).


Каждая из частей образца форматирования состоит из префикса ( NFPrefix ), целой части ( NFInteger ), необязательной дробной части ( NFFractional ) и суффикса ( NFSuffix ).

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

Пример 1¶

Префикс задает строку, которая будет предшествовать числу, это может быть последовательность любых неформатирующих символов ( NFChar ) плюс символ процента ( NFPercent ). Аналогично, суффикс будет следовать за числом, и он тоже не может содержать форматирующих символов (за исключением символа процента).

Пример 2¶

Если мы хотим заключить наше число, к примеру, в квадратные скобки, мы должны будем включить в его образец форматирования префикс » [ » и суффикс » ] «:

Нетерминал NFinteger определяет, как будет выглядеть целая часть числа. Он начинается несколькими символами NFOptDigit (по умолчанию » # «), показывающими позиции, в которых цифры необязательны, и состоит из символов NFReqDigit (по умолчанию » 0 «), показывающих позиции обязательных цифр, а также символа NFGroupDelim (по умолчанию » , «), показывающего позицию символа-разделителя групп цифр.

Пример 3¶

Замечание. Некоторые процессоры позволяют указывать несколько символов-разделителей. Однако даже в этом случае они учитывают только последний из этих символов.

Пример 4¶

Дробная часть числа, представленная нетерминалом NFFraction , начинается символом-разделителем целой и дробной части NFFractionDelim (по умолчанию » . «), продолжается последовательностью символов обязательных позиций цифр NFReqDigit и заканчивается последовательностью символов необязательных позиций NFOptDigit :

Пример 5¶

Продукция NFChar , использующаяся при определении префикса ( NFPrefix ) и суффикса ( NFSuffix ), может содержать любые неформатирующие символы:

К специальным форматирующим символам относятся следующие:

  • символ обязательной позиции цифры (по умолчанию «0»);
  • символ необязательной позиции цифры (по умолчанию «#»);
  • символ-разделитель образцов форматирования для положительного и отрицательного числа (по умолчанию «;»);
  • символ-разделитель целой и дробной части (по умолчанию «.»);
  • символ процента (по умолчанию «%»).

Перечислим их продукции:

Синтаксические правила, которые мы привели выше, пока не являются стандартными. Они корректно передают синтаксис образца форматирования, но являются более строгими, чем определения в документации языка Java.

Roland Bouman’s blog

Programming — Databases — Analytics

Wednesday, April 08, 2015

CSS tricks for (conditional) formatting of numbers and dates

A Stackoverflow question: conditionally hiding zero values in a table

Today I stumbled upon this question on stackoverflow: Is there a way to hide a data cell based on a specific value using just HTML/CSS? For example I have this code: Is there a way to hide the cells that are equal to $0 using HTML/CSS only? Let’s say instead of $0 I have a variable called fee that can be a variety of values: $0, $5, $20, etc. Is there a way to check what value it is and if it is found to be $0 can I then hide it? As it turns out, this is actually possible with HTML5 data attributes, the CSS :before or :after pseudo-class, a CSS content property using a value of the type attr() , and attribute-value selector syntax to control conditional formatting: In summary, the ingredients of the solution are:

  • Encode the cell values as a custom data attribute, for example: data-value . The actual cells are empty.
  • Make the cell value show up using the :after pseudo-class of the td element. This is done by setting the CSS content property to the value attr() . Values of this type take an attribute name between the parenthesis, so in our example this becomes attr( data-value ) .
  • Use the attribute-value selector syntax for conditional formatting. In our example the requirement was to «hide» the value of cells with an amount equal to «$0» . We can express this as td[ data-value = «$0» ] . And since we display the value through the content property of the :after pseudo-class, we have to add : after to our td selector and specify a content property of «» to override the previous rule that outputs the value using attr() .
Читать еще:  Php условие if

The result looks something like this:

Browser compatibility

Monetary amount formatting: red vs black

Consider a balance sheet of monetary amounts. Amounts should be right aligned, and we want the positive amounts to be displayed in black, and negative amounts in red: Note the data-monetary-amount ^= «-» syntax. This is a so-called substring matching attribute selector, which is specified in CSS 3. The comparison operator ^= tests whether the attribute value starts with a particular string, in this case the minus sign «-» , which indicates we have a negative amount.

CSS 3 specifies similar comparison operators for a postfix match ( $= ) and an instring or «mid» match ( *= ).

The result looks something like this:

Browser compatibility

A slightly less nice solution that works in CSS 2.1

Locale dependent date formatting

The elements we saw in the previous example can be used for basic locale dependent date formatting. Let’s keep it simple and format dates either in USA format, mon/d/yyyy, or in a format that is more easily understood outside the USA, d/mon/yyyy: This solution uses the HTML5 time -element. The time element can have a datetime attribute that contains the date/time in a machine readable format, and it may contain text content, which should be a human-readable representation of the date/time.

Now, personally, I do not think the HTML5 time element is an example of good or convenient design. At least, not from the perspective of the HTML5 author.

It is a great idea to require a machine-readable representation of the date. This potentially allows user agents to do useful things with the content. And allowing the user to manually specify the human-readable representation is also not a bad idea per se. But IMO, the time -element would have been much more useful if authors would be allowed to only specify the machine-readable representation of the date/time and, in absence of a manually entered human representation of the date/time, let the browser figure out how that date appears in the output in a human-readable representation. That way the browser could use information about the language of the document or document section to auto-format the date, or otherwise apply some user-preference. Another idea would be to allow the HTML author to control the output format using another attribute for a format string.

Anyway, this is not the case so we can try and see what we can do on our end. The solution above is as follows:

  • In the example above, a date is expressed using two time elements: one for the year-part and one for the month and day parts of the date. The year-part uses a non-negative integer for the datetime attribute, indicating a year. The mont/day-part uses a datetime attribute to represent a valid yearless date string. I nested the time element that represents the month and day part inside the one that represents the year. That said, it would have been much nicer if I could’ve just used a single time -element using a single datetime attribute containing all dateparts, but I couldn’t figure out how to manipulate such a value with CSS. So I settled for a less optimal solution, which is certainly more verbose. At least, it does not duplicate any data, which seems a requirement that we never should let go off.
  • The first two CSS rules ensure that month and day appear first (using float:left ) and the year appears last (using float: right ). The first CSS rule specifies that all time elements having a datetime attribute should float right. The way we set it up, this matches the time elements that match the year part. The second CSS rule uses the substring-matching attribute selector *= to check if the datetime attribute of the time element contains a hyphen. Since the hyphen separates the day and month parts in the yearless date string format, this rule will match all time elements that represent a month/day part of a date.
  • The remaining rules are required for formatting the month and date parts as well as the separators. (Wich is a slash, / ).
  • The prefix matching attribute selector ^= is used to test which month is identified by the prefix of the value of the datetime attribute. For each month, with prefixes 01 through 12 , there is a rule, and its content property is used to output the month abbreviation like jan , feb , mar etc.
  • The postfix matching attribute selector $= is used to test which day is identified by the postfix of the value of the datetime attribute. For each day, with postfixes 01 through 31 , there is a rule, and its content property is used to output the day number.
  • The upper set of rules matching the month-prefix and day-postfix are used to generate :after and :before pseudo-classes respectively to ensure that by default, the day part is displayed before the month part.
  • To accommodate the USA date format, the bottom set of rules was added. These are essentially a duplication of the prefix- and postfix matching rules for the month and day part respectively, but these rules have an initial selector part like this *[lang=»en-US»] to ensure that these rules are active only if the time element is contained in a section that was marked as being localized for the USA. For these rules, the month parts are used to generate :before pseudo-classes, and the day parts are used to generate :after pseudo-classes, thus reversing the default order of displaying the month and day part.
Читать еще:  Php if then

The result looks something like this:

Browser compatibility


I hope this was useful information. Personally I think we still have a long way to go before we can use a pure css solution to solve all our data formatting problems, and I believe that esp. for web-applications, programmatic solutions (either on the server or on the client side) are still essential to deliver an acceptable result.

That said, every little bit of functionality in CSS can help you build a solution, even if such a solution is still controlled or generated by a programmatic backend.

Any comments and feedback are greatly appreciated.

My New Knowledge

Python, IaC, algo trading, programming, server administration, Linux, PHP, CakePHP, PostgreSQL, MySQL, Joomla .

Sunday, November 9, 2008

Styling Excel cells with mso-number-format

2 decimals, negative numbers in red and signed
(1.56 -1.56 )


Thanks very helpful. Another bit of cell formatting. To turn off Wrap Text in the cell add the following attribute to your TD tag, style=’white-space:nowrap’

Very good site. it helps a lot in my work. thumbs up. great job!

Thank you bud. A great list.

How i can i applythe mso-number-format for differente columns?
For example: in the same excel file can i have the field date and the filed amount.

Thanks! You save my job =)

Hi i need text format in css, help me pls.

Petr, do you mean td

it worked for me thanks

How about possitve number?

i guess mso-number-format:»0″ is positive and negative integers

very informative! Good job

It doesn’t work with jsp.

that is for excel. you write a ‘table’, and style the ‘td’s with those css classes so that excel recognizes the style of the content

This is really helpful. Thanks for your post.

I have a formatted value of 1-5, when exported to excel it converts to 5-Jan. how can I use mso-number-format to maintain 1-5?

Anyone know where a reference list is with all the mso commands on it, like for text formatting, borders, alignment, etc??

I have scoured the depths of google and I only come up with the pages talking about specific commands, but never a comprehensive list.

I was once looking for such a list, and only arrived to the few copied in this post.

All I could find were these two sources for other mso commands:

There are a few here scattered around in the left side links under the heading, «Subelements of Shape»

Also, on this blog entry, there are several commands in the style tags of the XML code.

Great information. I was wondering what the heck does @ mean and now I know.

Thank you. This really helps!.

This comment has been removed by a blog administrator.

mso stand for.. ? anyone?

My simple ornament

. hahahaha, you rock!:-)

. wow — the [Red] trick is awsome! I incorporated it in my applicatins.

mso-number-format:»Percent» using this giving me 10000.00%
for value of 100.

Help or suggestion really appriciated.

when using PERCENT, Excel show 10% for a value of 0,1.

so divide values by 100 before applying format

good knowledge. beer:

Thank you! Solved my problem. I appreciate the sharing.

how to display 3.56 as 3 what is mso-number-format for it

It’s fine..i have used date format so when i click date cell the formatting is custom but it will should be date.. can u help me?

Can anyone help me on formatting long number similar to this 5402199999999999999 from html to excelsheet.
When I am using mso-number-format:0 in Style of a td tag, getting the number is excel as 5430689999999990000
But the same format mso-number-format:0 is working fine for this number

Ссылка на основную публикацию
ВсеИнструменты 220 Вольт