The NumberFormatter class

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

소개

Programs store and operate on numbers using a locale-independent binary representation. When displaying or printing a number it is converted to a locale-specific string. For example, the number 12345.67 is "12,345.67" in the US, "12 345,67" in France and "12.345,67" in Germany.

By invoking the methods provided by the NumberFormatter class, you can format numbers, currencies, and percentages according to the specified or default locale. NumberFormatter is locale-sensitive so you need to create a new NumberFormatter for each locale. NumberFormatter methods format primitive-type numbers, such as double and output the number as a locale-specific string.

For currencies you can use currency format type to create a formatter that returns a string with the formatted number and the appropriate currency sign. Of course, the NumberFormatter class is unaware of exchange rates so, the number output is the same regardless of the specified currency. This means that the same number has different monetary values depending on the currency locale. If the number is 9988776.65 the results will be:

  • 9 988 776,65 € in France
  • 9.988.776,65 € in Germany
  • $9,988,776.65 in the United States

In order to format percentages, create a locale-specific formatter with percentage format type. With this formatter, a decimal fraction such as 0.75 is displayed as 75%.

For more complex formatting, like spelled-out numbers, the rule-based number formatters are used.

클래스 개요

NumberFormatter {
/* 메소드 */
public __construct ( string $locale , int $style [, string $pattern ] )
public static NumberFormatter create ( string $locale , int $style [, string $pattern ] )
public string formatCurrency ( float $value , string $currency )
public string format ( number $value [, int $type ] )
public int getAttribute ( int $attr )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public string getLocale ([ int $type ] )
public string getPattern ( void )
public string getSymbol ( int $attr )
public string getTextAttribute ( int $attr )
public float parseCurrency ( string $value , string &$currency [, int &$position ] )
public mixed parse ( string $value [, int $type [, int &$position ]] )
public bool setAttribute ( int $attr , int $value )
public bool setPattern ( string $pattern )
public bool setSymbol ( int $attr , string $value )
public bool setTextAttribute ( int $attr , string $value )
}

예약 상수

These styles are used by the numfmt_create() to define the type of the formatter.

NumberFormatter::PATTERN_DECIMAL (integer)
Decimal format defined by pattern
NumberFormatter::DECIMAL (integer)
Decimal format
NumberFormatter::CURRENCY (integer)
Currency format
NumberFormatter::PERCENT (integer)
Percent format
NumberFormatter::SCIENTIFIC (integer)
Scientific format
NumberFormatter::SPELLOUT (integer)
Spellout rule-based format
NumberFormatter::ORDINAL (integer)
Ordinal rule-based format
NumberFormatter::DURATION (integer)
Duration rule-based format
NumberFormatter::PATTERN_RULEBASED (integer)
Rule-based format defined by pattern
NumberFormatter::DEFAULT_STYLE (integer)
Default format for the locale
NumberFormatter::IGNORE (integer)
Alias for PATTERN_DECIMAL

These constants define how the numbers are parsed or formatted. They should be used as arguments to numfmt_format() and numfmt_parse().

NumberFormatter::TYPE_DEFAULT (integer)
Derive the type from variable type
NumberFormatter::TYPE_INT32 (integer)
Format/parse as 32-bit integer
NumberFormatter::TYPE_INT64 (integer)
Format/parse as 64-bit integer
NumberFormatter::TYPE_DOUBLE (integer)
Format/parse as floating point value
NumberFormatter::TYPE_CURRENCY (integer)
Format/parse as currency value

Number format attribute used by numfmt_get_attribute() and numfmt_set_attribute().

NumberFormatter::PARSE_INT_ONLY (integer)
Parse integers only.
NumberFormatter::GROUPING_USED (integer)
Use grouping separator.
NumberFormatter::DECIMAL_ALWAYS_SHOWN (integer)
Always show decimal point.
NumberFormatter::MAX_INTEGER_DIGITS (integer)
Maximum integer digits.
NumberFormatter::MIN_INTEGER_DIGITS (integer)
Minimum integer digits.
NumberFormatter::INTEGER_DIGITS (integer)
Integer digits.
NumberFormatter::MAX_FRACTION_DIGITS (integer)
Maximum fraction digits.
NumberFormatter::MIN_FRACTION_DIGITS (integer)
Minimum fraction digits.
NumberFormatter::FRACTION_DIGITS (integer)
Fraction digits.
NumberFormatter::MULTIPLIER (integer)
Multiplier.
NumberFormatter::GROUPING_SIZE (integer)
Grouping size.
NumberFormatter::ROUNDING_MODE (integer)
Rounding Mode.
NumberFormatter::ROUNDING_INCREMENT (integer)
Rounding increment.
NumberFormatter::FORMAT_WIDTH (integer)
The width to which the output of format() is padded.
NumberFormatter::PADDING_POSITION (integer)
The position at which padding will take place. See pad position constants for possible argument values.
NumberFormatter::SECONDARY_GROUPING_SIZE (integer)
Secondary grouping size.
NumberFormatter::SIGNIFICANT_DIGITS_USED (integer)
Use significant digits.
NumberFormatter::MIN_SIGNIFICANT_DIGITS (integer)
Minimum significant digits.
NumberFormatter::MAX_SIGNIFICANT_DIGITS (integer)
Maximum significant digits.
NumberFormatter::LENIENT_PARSE (integer)
Lenient parse mode used by rule-based formats.

Number format text attribute used by numfmt_get_text_attribute() and numfmt_set_text_attribute().

NumberFormatter::POSITIVE_PREFIX (integer)
Positive prefix.
NumberFormatter::POSITIVE_SUFFIX (integer)
Positive suffix.
NumberFormatter::NEGATIVE_PREFIX (integer)
Negative prefix.
NumberFormatter::NEGATIVE_SUFFIX (integer)
Negative suffix.
NumberFormatter::PADDING_CHARACTER (integer)
The character used to pad to the format width.
NumberFormatter::CURRENCY_CODE (integer)
The ISO currency code.
NumberFormatter::DEFAULT_RULESET (integer)
The default rule set. This is only available with rule-based formatters.
NumberFormatter::PUBLIC_RULESETS (integer)
The public rule sets. This is only available with rule-based formatters. This is a read-only attribute. The public rulesets are returned as a single string, with each ruleset name delimited by ';' (semicolon).

Number format symbols used by numfmt_get_symbol() and numfmt_set_symbol().

NumberFormatter::DECIMAL_SEPARATOR_SYMBOL (integer)
The decimal separator.
NumberFormatter::GROUPING_SEPARATOR_SYMBOL (integer)
The grouping separator.
NumberFormatter::PATTERN_SEPARATOR_SYMBOL (integer)
The pattern separator.
NumberFormatter::PERCENT_SYMBOL (integer)
The percent sign.
NumberFormatter::ZERO_DIGIT_SYMBOL (integer)
Zero.
NumberFormatter::DIGIT_SYMBOL (integer)
Character representing a digit in the pattern.
NumberFormatter::MINUS_SIGN_SYMBOL (integer)
The minus sign.
NumberFormatter::PLUS_SIGN_SYMBOL (integer)
The plus sign.
NumberFormatter::CURRENCY_SYMBOL (integer)
The currency symbol.
NumberFormatter::INTL_CURRENCY_SYMBOL (integer)
The international currency symbol.
NumberFormatter::MONETARY_SEPARATOR_SYMBOL (integer)
The monetary separator.
NumberFormatter::EXPONENTIAL_SYMBOL (integer)
The exponential symbol.
NumberFormatter::PERMILL_SYMBOL (integer)
Per mill symbol.
NumberFormatter::PAD_ESCAPE_SYMBOL (integer)
Escape padding character.
NumberFormatter::INFINITY_SYMBOL (integer)
Infinity symbol.
NumberFormatter::NAN_SYMBOL (integer)
Not-a-number symbol.
NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL (integer)
Significant digit symbol.
NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL (integer)
The monetary grouping separator.

Rounding mode values used by numfmt_get_attribute() and numfmt_set_attribute() with NumberFormatter::ROUNDING_MODE attribute.

NumberFormatter::ROUND_CEILING (integer)
Rounding mode to round towards positive infinity.
NumberFormatter::ROUND_DOWN (integer)
Rounding mode to round towards zero.
NumberFormatter::ROUND_FLOOR (integer)
Rounding mode to round towards negative infinity.
NumberFormatter::ROUND_HALFDOWN (integer)
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
NumberFormatter::ROUND_HALFEVEN (integer)
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
NumberFormatter::ROUND_HALFUP (integer)
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
NumberFormatter::ROUND_UP (integer)
Rounding mode to round away from zero.

Pad position values used by numfmt_get_attribute() and numfmt_set_attribute() with NumberFormatter::PADDING_POSITION attribute.

NumberFormatter::PAD_AFTER_PREFIX (integer)
Pad characters inserted after the prefix.
NumberFormatter::PAD_AFTER_SUFFIX (integer)
Pad characters inserted after the suffix.
NumberFormatter::PAD_BEFORE_PREFIX (integer)
Pad characters inserted before the prefix.
NumberFormatter::PAD_BEFORE_SUFFIX (integer)
Pad characters inserted before the suffix.

Table of Contents

add a note add a note

User Contributed Notes 6 notes

up
34
giorgio dot liscio at email dot it
12 years ago
this class seems to be painful: it is not, formatting and parsing are highly customizable, but what you probably need is really simple:

if you want to localize a number use:

<?php
$a
= new \NumberFormatter("it-IT", \NumberFormatter::DECIMAL);
echo
$a->format(12345.12345) . "<br>"; // outputs 12.345,12
$a->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
$a->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 100); // by default some locales got max 2 fraction digits, that is probably not what you want
echo $a->format(12345.12345) . "<br>"; // outputs 12.345,12345
?>

if you want to print money use:

<?php
$a
= new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
echo
$a->format(12345.12345) . "<br>"; // outputs €12.345,12
?>

if you have money data stored as (for example) US dollars and you want to print them using the it-IT notation, you need to use

<?php
$a
= new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
echo
$a->formatCurrency(12345, "USD") . "<br>"; // outputs $ 12.345,00 and it is formatted using the italian notation (comma as decimal separator)
?>

another useful example about currency (how to obtain the currency name by a locale string):

<?php
$frontEndFormatter
= new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
$adminFormatter = new \NumberFormatter("en-US", \NumberFormatter::CURRENCY);
$symbol = $adminFormatter->getSymbol(\NumberFormatter::INTL_CURRENCY_SYMBOL); // got USD
echo $frontEndFormatter->formatCurrency(12345.12345$symbol) . "<br>";
?>
up
6
sudheer at binaryvibes dot co dot in
13 years ago
Sample script to print number in English.

<?php
$f
= new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo
$f->format(123456);

?>

Produces the result:
one hundred twenty-three thousand four hundred fifty-six
up
2
stan at dragnev dot ca
3 years ago
Here's an example of how to use PATTERN_DECIMAL to print a number with two fraction digits, use () for negative numbers and pad to five characters to the left of the decimal point, using spaces as the padding character:

<?php

$fmt
= new NumberFormatter("en-CA", NumberFormatter::PATTERN_DECIMAL, "* #####.00 ;(* #####.00)");
echo
$fmt->format(-45.1);

// Outputs: "  (45.10)"

?>

Note that the ; in the pattern denotes the beginning of a subpattern, which is used for negative numbers. Hence the brackets around the pattern after the semicolon.
up
1
AF
3 years ago
Please pay attention to the Arabic decimal separator (https://en.wikipedia.org/wiki/Decimal_separator#Other_numeral_systems).

All the following conditions are true:
<?php
(new \NumberFormatter("ar_AE", \NumberFormatter::DEFAULT_STYLE))->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL) === '٫';
(new \
NumberFormatter("ar_AE", \NumberFormatter::DEFAULT_STYLE))->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL) == '٫';

(new \
NumberFormatter("ar_AE", \NumberFormatter::DEFAULT_STYLE))->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL) !== ',';
(new \
NumberFormatter("ar_AE", \NumberFormatter::DEFAULT_STYLE))->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL) != ',';
?>
up
0
Joey
6 years ago
Be warned that this class sometimes lacks sufficient error output. I recently instantiated it while invalid pattern to the constructor.

    php -r '$nf = new \NumberFormatter("tlh-KX.UTF8", \NumberFormatter::IGNORE, "{,,#;#}");var_dump($nf->format(5));'

    Fatal error: Call to a member function format() on null in Command line code on line 1

Rather than emitting an error message or throwing an exception null is returned after calling new.

I'm not sure if it's fixed in PHP 7 but it's something to watch out for. Make sure you check your parameters very closely.
up
-4
Adam
7 years ago
Good to know Numberformatter::SPELLOUT using soft hypens.

So, if you want to avoid it use preg_replace:

<?php
$azaz
= new NumberFormatter("hu-HU", NumberFormatter::SPELLOUT);
$text = preg_replace('~\x{00AD}~u', '', $azaz->format(123456));
print
$text;
?>
Output without preg_replace:
egy-­száz-­huszon-­három-­ezer négy-­száz-­ötven-­hat

Output with preg_replace:
egyszázhuszonháromezer négyszázötvenhat
To Top