本文整理汇总了PHP中NumberFormatter::create方法的典型用法代码示例。如果您正苦于以下问题:PHP NumberFormatter::create方法的具体用法?PHP NumberFormatter::create怎么用?PHP NumberFormatter::create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类NumberFormatter
的用法示例。
在下文中一共展示了NumberFormatter::create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: test_rounding
function test_rounding($locale, $digits, $mode = null)
{
$formatter = NumberFormatter::create($locale, NumberFormatter::DEFAULT_STYLE);
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $digits);
if ($mode !== null) {
$formatter->setAttribute(NumberFormatter::ROUNDING_MODE, $mode);
}
$values = array(1.23, 1.2327, 1.2372, 1.235, -1.23, -1.2327, -1.2372, -1.235);
foreach ($values as $value) {
echo $value;
echo " -> ";
$to_print = $formatter->format($value);
//
// Remove the Unicode Character 'LEFT-TO-RIGHT MARK' (U+200E)
// which some versions of ICU use for Farsi.
// See http://www.fileformat.info/info/unicode/char/200e/index.htm
//
$to_print = str_replace("", "", $to_print);
//
// Replace the Unicode Character 'MINUS SIGN' (U+2212)
// which some versions of ICU use for Farsi.
// See http://www.fileformat.info/info/unicode/char/2212/index.htm
//
$to_print = str_replace("−", "-", $to_print);
echo $to_print;
echo "\n";
}
}
示例2: testCurrencyCodeOption
public function testCurrencyCodeOption()
{
$v = new CurrencyValidator(['locale' => 'it_IT']);
$this->assertNull($v->getCurrencyCode());
$v->isValid('1.234,61 €');
$formatter = \NumberFormatter::create('it_IT', \NumberFormatter::CURRENCY);
$this->assertEquals($v->getCurrencyCode(), $formatter->getTextAttribute(\NumberFormatter::CURRENCY_CODE));
$v = new CurrencyValidator(['locale' => 'it_IT']);
$v->setCurrencyCode('USD');
$this->assertEquals('USD', $v->getCurrencyCode());
}
示例3: testSetupCurrencyCode
public function testSetupCurrencyCode()
{
$reflMethod = new \ReflectionMethod('MoneyLaundry\\Filter\\AbstractFilter', 'setupCurrencyCode');
$reflMethod->setAccessible(true);
$mock = $this->getMockBuilder('MoneyLaundry\\Filter\\AbstractFilter')->enableProxyingToOriginalMethods()->setMethods(['getFormatter', 'getCurrencyCode'])->getMockForAbstractClass();
$formatter = \NumberFormatter::create('it_IT', \NumberFormatter::CURRENCY);
$mock->expects($this->at(0))->method('getFormatter')->willReturn($formatter);
$mock->expects($this->at(1))->method('getCurrencyCode')->willReturn($formatter->getTextAttribute(\NumberFormatter::CURRENCY_CODE));
$this->assertSame($formatter->getTextAttribute(\NumberFormatter::CURRENCY_CODE), $reflMethod->invoke($mock));
$reflMethod->setAccessible(false);
}
示例4: valuesProvider
/**
* @return array
*/
public function valuesProvider()
{
$data = [];
foreach ($this->locales as $locale) {
foreach ($this->values as $i) {
$e = \NumberFormatter::create($locale, \NumberFormatter::SCIENTIFIC)->format($i, \NumberFormatter::TYPE_DEFAULT);
$n = \NumberFormatter::create($locale, \NumberFormatter::DECIMAL)->format($i, \NumberFormatter::TYPE_DEFAULT);
$data[] = [true, $e, $locale];
$data[] = [false, $n, $locale];
}
}
return $data;
}
示例5: crt
function crt($t, $l, $s)
{
switch (true) {
case $t == "O":
return new NumberFormatter($l, $s);
break;
case $t == "C":
return NumberFormatter::create($l, $s);
break;
case $t == "P":
return numfmt_create($l, $s);
break;
}
}
示例6: twig_get_number_formatter
/**
* Gets a number formatter instance according to given locale and formatter.
*
* @param string $locale Locale in which the number would be formatted
* @param int $style Style of the formatting
*
* @return NumberFormatter A NumberFormatter instance
*/
function twig_get_number_formatter($locale, $style)
{
static $formatter, $currentStyle;
$locale = $locale !== null ? $locale : Locale::getDefault();
if ($formatter && $formatter->getLocale() === $locale && $currentStyle === $style) {
// Return same instance of NumberFormatter if parameters are the same
// to those in previous call
return $formatter;
}
static $styleValues = array('decimal' => NumberFormatter::DECIMAL, 'currency' => NumberFormatter::CURRENCY, 'percent' => NumberFormatter::PERCENT, 'scientific' => NumberFormatter::SCIENTIFIC, 'spellout' => NumberFormatter::SPELLOUT, 'ordinal' => NumberFormatter::ORDINAL, 'duration' => NumberFormatter::DURATION);
if (!isset($styleValues[$style])) {
throw new Twig_Error_Syntax(sprintf('The style "%s" does not exist. Known styles are: "%s"', $style, implode('", "', array_keys($styleValues))));
}
$currentStyle = $style;
$formatter = NumberFormatter::create($locale, $styleValues[$style]);
return $formatter;
}
示例7: filter
/**
* Returns the result of filtering $value
*
* @param mixed $value
* @return mixed
*/
public function filter($value)
{
// Store original value
$unfilteredValue = $value;
if (is_string($value)) {
// Initialization
$formatter = $this->getFormatter();
// Disable scientific notation
$formatter->setSymbol(\NumberFormatter::EXPONENTIAL_SYMBOL, null);
if ($this->getBreakingSpaceAllowed()) {
// Replace spaces with NBSP (non breaking spaces)
$value = str_replace(" ", " ", $value);
// FIXME? can be removed
}
// Parse as currency
ErrorHandler::start();
$position = 0;
$currencyCode = $this->setupCurrencyCode();
if ($this->getCurrencyCorrectness()) {
// The following parsing mode allows the predefined currency code ONLY.
// Also it should be more strict and faster than parseCurrency.
$result = $formatter->parse($value, \NumberFormatter::TYPE_DOUBLE, $position);
} else {
// The following parsing mode can work with multiple currencies.
$result = $formatter->parseCurrency($value, $resultCurrencyCode, $position);
}
$fractionDigits = $formatter->getAttribute(\NumberFormatter::FRACTION_DIGITS);
// Input is a valid currency and the result is within the codomain?
if ($result !== false && (is_float($result) && !is_infinite($result) && !is_nan($result))) {
ErrorHandler::stop();
// Exit if the parsing has finished before the end of the input
if ($position < grapheme_strlen($value)) {
return $unfilteredValue;
}
// Retrieve currency symbol for the given locale and currency code
$currencySymbol = $this->getFirstCurrencySymbol($this->getLocale(), $currencyCode);
// Exit if the currency correctness is mandatory and the currency symbol is not present in the input
if ($this->getCurrencyCorrectness() && grapheme_strpos($value, $currencySymbol) === false) {
return $unfilteredValue;
}
if ($this->getScaleCorrectness()) {
$countedDecimals = $this->countDecimalDigits($value, $formatter->getSymbol(\NumberFormatter::MONETARY_SEPARATOR_SYMBOL), $currencySymbol);
// Exit if the number of decimal digits (i.e., the scale) does not match the requirement
if ($fractionDigits !== $countedDecimals) {
return $unfilteredValue;
}
}
// Here we have a perfectly parsed (pattern correct, currency correct, scale correct) currency amount
return $result;
}
// At this stage result is FALSE and input probably is a not canonical currency amount
// Check if the currency symbol is mandatory (assiming 'parse MODE')
if ($this->getCurrencyCorrectness()) {
ErrorHandler::stop();
return $unfilteredValue;
}
// Retrieve symbols
$symbolKeys = [self::CURRENCY_SYMBOL, self::GROUP_SEPARATOR_SYMBOL, self::SEPARATOR_SYMBOL, self::INFINITY_SYMBOL, self::NAN_SYMBOL, self::POSITIVE_PREFIX, self::POSITIVE_SUFFIX, self::NEGATIVE_PREFIX, self::NEGATIVE_SUFFIX, self::FRACTION_DIGITS];
$symbols = [];
foreach ($symbolKeys as $symbol) {
$symbols[$symbol] = $this->getSymbol($symbol);
}
// Regex components
$regexSymbols = array_filter(array_unique(array_values($symbols)));
$numbers = $this->getRegexComponent(self::REGEX_NUMBERS);
$flags = $this->getRegexComponent(self::REGEX_FLAGS);
// Build allowed chars regex
$allowedChars = sprintf('#^[%s]+$#%s', $numbers . implode('', array_map('preg_quote', $regexSymbols)), $flags);
// FIXME: pay attention to NaN and INF symbols here
// Check that value contains only allowed characters (digits, group and decimal separator)
$result = false;
if (preg_match($allowedChars, $value)) {
$decimal = \NumberFormatter::create($this->getLocale(), \NumberFormatter::DECIMAL);
// Get decimal place info
// FIXME: parse and parseCurrancy could use different symbols
// when used with non default currency code
$currencySymbol = $this->getFirstCurrencySymbol($this->getLocale(), $currencyCode);
$numDecimals = $this->countDecimalDigits($value, $symbols[self::SEPARATOR_SYMBOL], $currencySymbol);
// Check if the number of decimal digits match the requirement
if ($this->getScaleCorrectness() && $numDecimals !== $fractionDigits) {
return $unfilteredValue;
}
// Ignore spaces
$value = str_replace(" ", '', $value);
// Substitute negative currency representation with negative number representation
$decimalNegPrefix = $decimal->getTextAttribute(\NumberFormatter::NEGATIVE_PREFIX);
$decimalNegSuffix = $decimal->getTextAttribute(\NumberFormatter::NEGATIVE_SUFFIX);
$currencyNegPrefix = $symbols[self::NEGATIVE_PREFIX];
$currencyNegSuffix = $symbols[self::NEGATIVE_SUFFIX];
if ($decimalNegPrefix !== $currencyNegPrefix && $decimalNegSuffix !== $currencyNegSuffix) {
$regex = sprintf('#^%s([%s%s%s]+)%s$#%s', preg_quote($currencyNegPrefix), $numbers, preg_quote($symbols[self::SEPARATOR_SYMBOL]), preg_quote($symbols[self::GROUP_SEPARATOR_SYMBOL]), preg_quote($currencyNegSuffix), $flags);
$value = preg_replace($regex, $decimalNegPrefix . '\\1' . $decimalNegSuffix, $value);
}
// Try to parse as a simple decimal (formatted) number
//.........这里部分代码省略.........
示例8: testCreateIntl
public function testCreateIntl()
{
$this->skipIfIntlExtensionIsNotLoaded();
$this->assertInstanceOf('\\NumberFormatter', \NumberFormatter::create('en', \NumberFormatter::DECIMAL));
}
示例9:
<?php
$formatter = NumberFormatter::create("fa_IR", NumberFormatter::DEFAULT_STYLE);
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 2);
echo $formatter->format(1.23);
echo "\n";
echo $formatter->format("10.345");
echo "\n";
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
$formatter->setAttribute(NumberFormatter::ROUNDING_MODE, NumberFormatter::ROUND_HALFUP);
echo $formatter->format(123450.67);
echo "\n";
echo $formatter->format("123456788.89");
echo "\n";
示例10: getCurrency
/**
* Returns a formated currency
*
* @param float $value The number to format
* @param string $currency The target currency to format
*
* @return string The resulting string
*/
public function getCurrency($value, $currency = 'EUR')
{
$this->numberFormatter = \NumberFormatter::create($this->current, \NumberFormatter::CURRENCY);
return $this->getNumberFormatter()->formatCurrency($value, $currency);
}
示例11: testCreate
public function testCreate()
{
$this->assertInstanceOf('\\NumberFormatter', \NumberFormatter::create('en', \NumberFormatter::DECIMAL));
}
示例12: _setReleaseNotes
/**
* Populates the release information for the current component.
*/
protected function _setReleaseNotes()
{
if (!($file = $this->_component->getReleaseNotesPath())) {
return;
}
if (basename($file) == 'release.yml') {
$version = Components_Helper_Version::parsePearVersion($this->_component->getVersion());
$description = Horde_String::lower($version->description);
if (strpos($description, 'release') === false) {
$description .= ' release';
}
$infofile = dirname($file) . '/horde.yml';
try {
$info = Horde_Yaml::loadFile($infofile);
} catch (Horde_Yaml_Exception $e) {
throw new Components_Exception($e);
}
$this->_notes['name'] = $info['name'];
if (isset($info['list'])) {
$this->_notes['list'] = $info['list'];
}
try {
$release = Horde_Yaml::loadFile($file);
} catch (Horde_Yaml_Exception $e) {
throw new Components_Exception($e);
}
if (isset($release['branch'])) {
$this->_notes['branch'] = $release['branch'];
}
$this->_notes['security'] = $release['security'];
if (is_array($release['changes'])) {
if (!is_array(reset($release['changes']))) {
$release['changes'] = array($release['changes']);
}
} else {
$release['changes'] = array();
}
$currentSection = null;
$changes = '';
foreach ($release['changes'] as $section => $sectionChanges) {
if ($section != $currentSection) {
$changes .= "\n\n" . $section . ':';
$currentSection = $section;
}
foreach ($sectionChanges as $change) {
$changes .= "\n * " . $change;
}
}
switch ($version->description) {
case 'Final':
$prerelease = '';
break;
case 'Alpha':
case 'Beta':
$prerelease = '
This is a preview version that should not be used on production systems. This version is considered feature complete but there might still be a few bugs. You should not use this preview version over existing production data.
We encourage widespread testing and feedback via the mailing lists or our bug tracking system. Updated translations are very welcome, though some strings might still change before the final release.
';
break;
case 'Release Candidate':
$prerelease = sprintf('
Barring any problems, this code will be released as %s %s.
Testing is requested and comments are encouraged. Updated translations would also be great.
', $info['name'], $version->version);
break;
}
$this->_notes['changes'] = sprintf('The Horde Team is pleased to announce the %s%s of the %s version %s.
%s
%s
For upgrading instructions, please see
http://www.horde.org/apps/%s/docs/UPGRADING
For detailed installation and configuration instructions, please see
http://www.horde.org/apps/%s/docs/INSTALL
%s
The major changes compared to the %s version %s are:%s', $version->subversion ? NumberFormatter::create('en_US', NumberFormatter::ORDINAL)->format($version->subversion) . ' ' : '', $description, $info['full'], $version->version, $info['description'], $prerelease, $info['id'], $info['id'], !empty($release['additional']) ? "\n" . implode("\n\n", $release['additional']) . "\n" : '', $info['name'], $this->_component->getPreviousVersion(), $changes);
} else {
$this->_notes = (include $file);
}
}
示例13:
<?php
$formatter = NumberFormatter::create("en_US", NumberFormatter::DEFAULT_STYLE);
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 2);
echo $formatter->format(1.23);
echo "\n";
echo $formatter->format("10.345");
echo "\n";
$formatter = NumberFormatter::create("en_US", NumberFormatter::DEFAULT_STYLE);
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
$formatter->setAttribute(NumberFormatter::ROUNDING_MODE, NumberFormatter::ROUND_HALFUP);
echo $formatter->format(123450.67);
echo "\n";
echo $formatter->format("123456788.89");
echo "\n";
示例14: valuesProvider
/**
* Generate dataset.
*
* Formats:
* - (positive and negative) currency amounts with their own currency symbol
* - (positive and negative) currency amounts with ISO currency symbol
* - (positive and negative) numbers (without currency symbol)
* - (positive and negative) numbers expressed in scientific notation (without currency symbol)
*
* @return array
*/
public function valuesProvider()
{
$data = [];
$values = [0, 0.1, 0.01, 1000, 1234.61, 12345678.9];
$values = array_unique(array_merge($values, array_map(function ($i) {
return -$i;
}, $values)));
foreach ($this->locales as $locale) {
$formatter = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
$currencySymbol = $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);
$isoSymbol = $formatter->getTextAttribute(\NumberFormatter::CURRENCY_CODE);
$groupSep = $formatter->getSymbol(\NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL);
$numDecimals = $formatter->getAttribute(\NumberFormatter::FRACTION_DIGITS);
$posPre = $formatter->getTextAttribute(\NumberFormatter::POSITIVE_PREFIX);
$negPre = $formatter->getTextAttribute(\NumberFormatter::NEGATIVE_PREFIX);
$posSuf = $formatter->getTextAttribute(\NumberFormatter::POSITIVE_SUFFIX);
$negSuf = $formatter->getTextAttribute(\NumberFormatter::NEGATIVE_SUFFIX);
$exponantiatior = \NumberFormatter::create($locale, \NumberFormatter::SCIENTIFIC);
foreach ($values as $value) {
// Restore currency symbol
$formatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, $currencySymbol);
if (is_float($value)) {
// If value is float and current currency does not have cents, jump it
if ($numDecimals === 0) {
continue;
}
// Create a currency with less decimal places then required (w/ currency symbol)
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $numDecimals - 1);
$currency = preg_replace('/^[\\xC2\\xA0\\s]+|[\\xC2\\xA0\\s]+$/u', '', $formatter->format($value));
// echo $currency . PHP_EOL;
$data[] = [$locale, true, true, $currency, $currency];
// Not filtered
$data[] = [$locale, true, false, $currency, $currency];
// Not filtered
$data[] = [$locale, false, false, (double) sprintf('%.' . ($numDecimals - 1) . 'f', $value), $currency];
// Filtered
$data[] = [$locale, false, true, (double) sprintf('%.' . ($numDecimals - 1) . 'f', $value), $currency];
// Filtered
// Create a currency with less decimal places then required (w/o currency symbol)
$currency = preg_replace('#' . preg_quote($currencySymbol) . '#u', '', $currency);
$currency = preg_replace('/^[\\xC2\\xA0\\s]+|[\\xC2\\xA0\\s]+$/u', '', $currency);
// echo $currency . PHP_EOL;
$data[] = [$locale, true, true, $currency, $currency];
// Not filtered
$data[] = [$locale, true, false, $currency, $currency];
// Not filtered
$data[] = [$locale, false, false, (double) sprintf('%.' . ($numDecimals - 1) . 'f', $value), $currency];
// Filtered
$data[] = [$locale, false, true, $currency, $currency];
// Not filtered
// Create a currency with more decimal places then required (w/ currency symbol)
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $numDecimals + 1);
$currency = preg_replace('/^[\\xC2\\xA0\\s]+|[\\xC2\\xA0\\s]+$/u', '', $formatter->format($value));
// echo $currency . PHP_EOL;
$data[] = [$locale, true, true, $currency, $currency];
// Not filtered
$data[] = [$locale, true, false, $currency, $currency];
// Not filtered
$data[] = [$locale, false, false, (double) sprintf('%.' . ($numDecimals + 1) . 'f', $value), $currency];
// Filtered
$data[] = [$locale, false, true, (double) sprintf('%.' . ($numDecimals + 1) . 'f', $value), $currency];
// Filtered
// Create a currency with more decimal places then required (w/o currency symbol)
$currency = preg_replace('#' . preg_quote($currencySymbol) . '#u', '', $currency);
$currency = preg_replace('/^[\\xC2\\xA0\\s]+|[\\xC2\\xA0\\s]+$/u', '', $currency);
// echo $currency . PHP_EOL;
$data[] = [$locale, true, true, $currency, $currency];
// Not filtered
$data[] = [$locale, true, false, $currency, $currency];
// Not filtered
$data[] = [$locale, false, false, (double) sprintf('%.' . ($numDecimals + 1) . 'f', $value), $currency];
// Filtered
$data[] = [$locale, false, true, $currency, $currency];
// Not filtered
}
// Restore correct number of maximum decimal places
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $numDecimals);
// Create completely formatted currency value (w/ currency symbol)
$currency = $formatter->formatCurrency($value, $isoSymbol);
// echo $currency . PHP_EOL;
$data[] = [$locale, true, true, $value, $currency];
// Filtered
// Create currency value with letters inside
$randomPos = rand(0, grapheme_strlen($currency) - 1);
$currency = grapheme_substr($currency, 0, $randomPos) . 'X' . grapheme_substr($currency, $randomPos);
// echo $currency . PHP_EOL;
$daa[] = [$locale, true, true, $currency, $currency];
// Not filtered
// Create currency value (w/ currency symbol) (w/o group separators)
//.........这里部分代码省略.........
示例15: testChangeFormatterOnFly
public function testChangeFormatterOnFly()
{
$filter = new Uncurrency('it_IT');
$custom = \NumberFormatter::create('en_US', \NumberFormatter::CURRENCY);
$filter->setFormatter($custom);
$this->assertEquals('en_US', $filter->getLocale());
}