Example #1
1
 /**
  * Retorna número no formato brasileiro (locale: pt_BR, currency: BRL) por extenso
  * 
  * @param number $number 
  * @return string no formato brasileiro (locale: pt_BR, currency: BRL) por extenso
  */
 public function porExtenso($number)
 {
     if (!is_numeric($number)) {
         return false;
     }
     $numero_extenso = '';
     $arr = explode(".", $number);
     $inteiro = $arr[0];
     if (isset($arr[1])) {
         $decimos = strlen($arr[1]) == 1 ? $arr[1] . '0' : $arr[1];
     }
     $fmt = new \NumberFormatter('br', \NumberFormatter::SPELLOUT);
     if (is_array($arr)) {
         $numero_extenso = $fmt->format($inteiro) . ' reais';
         if (isset($decimos) && $decimos > 0) {
             $numero_extenso .= ' e ' . $fmt->format($decimos) . ' centavos';
         }
     }
     return $numero_extenso;
 }
 /**
  * @param VisitorInterface $visitor
  * @param FloatType        $data
  * @param array            $type
  * @param Context          $context
  *
  * @return mixed|void
  */
 public function serializeFloatType(VisitorInterface $visitor, FloatType $data, array $type, Context $context)
 {
     $numberFormatter = new \NumberFormatter($this->getLocale($type), $this->getFormat($type));
     if ($visitor instanceof XmlSerializationVisitor && false === $this->xmlCData) {
         return $visitor->visitSimpleString($numberFormatter->format($data->getValue()), $type, $context);
     }
     return $visitor->visitString($numberFormatter->format($data->getValue()), $type, $context);
 }
Example #3
0
 public function convert()
 {
     $formatter = new \NumberFormatter($this->locale, \NumberFormatter::PATTERN_DECIMAL);
     foreach ($this->binaryPrefixes as $size => $unitPattern) {
         if ($size <= $this->number) {
             $value = $this->number >= self::CONVERT_THRESHOLD ? $this->number / (double) $size : $this->number;
             $formatter->setPattern($unitPattern);
             return $formatter->format($value);
         }
     }
     return $formatter->format($this->number);
 }
Example #4
0
 public function render(\Erebot\IntlInterface $translator)
 {
     $locale = $translator->getLocale(\Erebot\IntlInterface::LC_NUMERIC);
     $formatter = new \NumberFormatter($locale, \NumberFormatter::IGNORE);
     $result = (string) $formatter->format($this->value, \NumberFormatter::TYPE_INT32);
     return $result;
 }
Example #5
0
 public function bytesToHuman($bytes, $precision = 2)
 {
     $suffixes = ['bytes', 'kB', 'MB', 'GB', 'TB'];
     $formatter = new \NumberFormatter($this->translator->getLocale(), \NumberFormatter::PATTERN_DECIMAL, 0 === $precision ? '#' : '.' . str_repeat('#', $precision));
     $exp = floor(log($bytes, 1024));
     return $formatter->format($bytes / pow(1024, floor($exp))) . ' ' . $this->translator->trans($suffixes[$exp]);
 }
Example #6
0
 /**
  * Formatação de numero decimal
  * @param float/integer $value
  * @param integer $precision
  * @param string $language
  * @return float
  */
 public static function decimalNumber($value, $precision = 2, $language = 'pt_BR')
 {
     $valDecimal = new \NumberFormatter($language, \NumberFormatter::DECIMAL);
     $valDecimal->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $precision);
     $valDecimal->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $precision);
     return $valDecimal->format((double) $value, \NumberFormatter::TYPE_DOUBLE);
 }
 /**
  * localized format for money with the NumberFormatter class in Decimal mode
  * without currency symbol
  * like 1.234,56
  *
  * @param Money $money
  * @param null  $locale
  * @return bool|string
  */
 public function formatI18nDecimal(Money $money, $locale = null)
 {
     if ($locale === null) {
         $locale = $this->locale;
     }
     $formatter = new \NumberFormatter($locale, \NumberFormatter::DECIMAL);
     return $formatter->format($money->getConvertedAmount());
 }
Example #8
0
 /**
  * Retorna número por extenso
  * @param int $number 
  * @return string número por extenso
  */
 public function porExtenso($number)
 {
     if (!is_numeric($number)) {
         return false;
     }
     $fmt = new \NumberFormatter('br', \NumberFormatter::SPELLOUT);
     return $fmt->format($number);
 }
Example #9
0
 /**
  * 数值转为中文拼读
  */
 public static function spell($number, $capital = false)
 {
     $formatter = new \NumberFormatter('zh_CN', \NumberFormatter::SPELLOUT);
     $sentence = $formatter->format($number);
     if ($capital) {
         $sentence = self::mbStrtr($sentence, self::$chars, self::$caps);
     }
     return $sentence;
 }
Example #10
0
 public function render(\Erebot\IntlInterface $translator)
 {
     $locale = $translator->getLocale(\Erebot\IntlInterface::LC_NUMERIC);
     $formatter = new \NumberFormatter($locale, \NumberFormatter::DECIMAL);
     $formatter->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
     $formatter->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 100);
     $result = (string) $formatter->format($this->value);
     return $result;
 }
 public static function Repeat($times)
 {
     $list = new ArrayList();
     $formatter = new NumberFormatter('en-NZ', NumberFormatter::SPELLOUT);
     for ($i = 1; $i <= $times; $i++) {
         $list->push(array('Num' => $i, 'Word' => ucwords(strtolower($formatter->format($i)))));
     }
     return $list;
 }
 /**
  * {@inheritdoc}
  */
 public function format($value)
 {
     $uiLocale = $this->getUiLocale();
     if (null === $uiLocale) {
         return $value;
     }
     $numberFormatter = new \NumberFormatter($uiLocale, \NumberFormatter::DECIMAL);
     $numberFormatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->getDecimalCount($value));
     return $numberFormatter->format($value);
 }
Example #13
0
function smarty_function_numberDecimal(array $params, Smarty_Internal_Template $template)
{
    $value = $params['value'];
    if (!is_numeric($value)) {
        throw new CM_Exception_Invalid('Invalid non-numeric value');
    }
    /** @var CM_Frontend_Render $render */
    $render = $template->getTemplateVars('render');
    $formatter = new NumberFormatter($render->getLocale(), NumberFormatter::DECIMAL);
    return $formatter->format($value);
}
 /**
  * Format the specified number to a string with the specified number of
  * fractional digits.
  *
  * @param
  *        	double d
  *        	The number to format.
  * @param
  *        	int digits
  *        	The number of fractional digits.
  * @return string The number formatted as a string.
  */
 public function format($d, $digits)
 {
     $this->synchronized(function ($thread) {
         if (is_infinite($d) || is_nan($d)) {
             return "0";
         }
         $this->numberFormatter->setAttribute(\NumberFormatter::GROUPING_USED, false);
         $this->numberFormatter->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $digits);
         return $this->numberFormatter->format($d);
     });
 }
Example #15
0
 private function entityToHtml($ent = null, $html = '')
 {
     //debug($ent);
     //die();
     $spellf = new \NumberFormatter("es", \NumberFormatter::SPELLOUT);
     $totalImporte = array_sum(array_column($ent->cuotas_polizas, 'pagado'));
     $html = str_replace("[NroRecibo]", $ent->id + $this->primerRecibo, $html);
     $html = str_replace("[Fecha]", $ent->created, $html);
     $html = str_replace("[Cliente]", $ent->client->razonSocial, $html);
     $html = str_replace("[TotalPalabras]", $spellf->format($ent->cuotas_polizas[0]['pagado']), $html);
     return $html;
 }
 /**
  * {@inheritdoc}
  */
 public function convertDefaultToLocalizedFromLocale($number, $locale)
 {
     if (null === $number || '' === $number) {
         return $number;
     }
     $numberFormatter = new \NumberFormatter($locale, \NumberFormatter::DECIMAL);
     if (is_numeric($number) && floor($number) != $number) {
         $numberFormatter->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 2);
         $numberFormatter->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 4);
     }
     return $numberFormatter->format($number);
 }
Example #17
0
 public function render(\Erebot\IntlInterface $translator)
 {
     $locale = $translator->getLocale(\Erebot\IntlInterface::LC_MESSAGES);
     $coreTranslator = new \Erebot\Intl('Erebot\\Styling');
     $coreTranslator->setLocale(\Erebot\IntlInterface::LC_MESSAGES, $locale);
     // DO NOT CHANGE THE CODE BELOW, ESPECIALLY COMMENTS & WHITESPACES.
     // It has all been carefully crafted to make both xgettext and
     // PHP_CodeSniffer happy! Also, it avoids relying on OS line endings
     // as it breaks xgettext on at least Windows platforms.
     $rule = $coreTranslator->_("%with-words:\n" . "    0: 0 seconds;\n" . "    1: 1 second;\n" . "    2: =#0= seconds;\n" . "    60/60: <%%min<;\n" . "    61/60: <%%min<, >%with-words>;\n" . "    3600/60: <%%hr<;\n" . "    3601/60: <%%hr<, >%with-words>;\n" . "    86400/86400: <%%day<;\n" . "    86401/86400: <%%day<, >%with-words>;\n" . "    604800/604800: <%%week<;\n" . "    604801/604800: <%%week<, >%with-words>;\n" . "%%min:\n" . "    1: 1 minute;\n" . "    2: =#0= minutes;\n" . "%%hr:\n" . "    1: 1 hour;\n" . "    2: =#0= hours;\n" . "%%day:\n" . "    1: 1 day;\n" . "    2: =#0= days;\n" . "%%week:\n" . "    1: 1 week;\n" . "    2: =#0= weeks;");
     $formatter = new \NumberFormatter($locale, \NumberFormatter::PATTERN_RULEBASED, $rule);
     return (string) $formatter->format($this->value);
 }
Example #18
0
 /**
  * {@inheritdoc}
  */
 public function format($value, array $options = [])
 {
     if (!is_numeric($value)) {
         throw new InvalidTypeException(sprintf('The number formatter expects a numeric value, got "%s".', is_object($value) ? get_class($value) : gettype($value)));
     }
     $scale = isset($options['scale']) ? $options['scale'] : 2;
     $rounding = isset($options['rounding']) ? $options['rounding'] : \NumberFormatter::ROUND_HALFUP;
     $grouping = isset($options['grouping']) ? $options['grouping'] : false;
     $formatter = new \NumberFormatter($this->localeContext->getLocale(), \NumberFormatter::DECIMAL);
     $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $scale);
     $formatter->setAttribute(\NumberFormatter::ROUNDING_MODE, $rounding);
     $formatter->setAttribute(\NumberFormatter::GROUPING_USED, $grouping);
     return str_replace(" ", ' ', $formatter->format($value));
 }
Example #19
0
 /**
  * {@inheritdoc}
  */
 public function formatAmount(CurrencyInterface $currency, $amount, $language_type = LanguageInterface::TYPE_CONTENT)
 {
     $currency_locale = $this->localeDelegator->resolveCurrencyLocale();
     $decimal_position = strpos($amount, '.');
     $number_of_decimals = $decimal_position !== FALSE ? strlen(substr($amount, $decimal_position + 1)) : 0;
     $formatter = new \NumberFormatter($currency_locale->getLocale(), \NumberFormatter::PATTERN_DECIMAL, $currency_locale->getPattern());
     $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $number_of_decimals);
     $formatter->setSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $currency_locale->getDecimalSeparator());
     $formatter->setSymbol(\NumberFormatter::MONETARY_SEPARATOR_SYMBOL, $currency_locale->getDecimalSeparator());
     $formatter->setSymbol(\NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $currency_locale->getGroupingSeparator());
     $formatter->setSymbol(\NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL, $currency_locale->getGroupingSeparator());
     $formatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, $currency->getSign());
     $formatter->setSymbol(\NumberFormatter::INTL_CURRENCY_SYMBOL, $currency->getCurrencyCode());
     return $formatted = $formatter->format($amount);
 }
Example #20
0
 public static function localeNumberFormat($number, $isMoney = false, $lg = '')
 {
     if ($lg == '') {
         $lg = self::$locale;
     }
     if ($number == '') {
         return $number;
     }
     if ($isMoney) {
         $fmt = new \NumberFormatter($lg, \NumberFormatter::CURRENCY);
         return $fmt->format($number);
     } else {
         $fmt = new \NumberFormatter($lg, \NumberFormatter::DECIMAL);
         return $fmt->format($number);
     }
 }
Example #21
0
 private function format()
 {
     $numberFormatter = new \NumberFormatter(\Locale::getDefault(), \NumberFormatter::CURRENCY);
     $result = $numberFormatter->format($this->getValue());
     if ($this->format !== null || self::$globalFormat !== null) {
         // need a special format?
         if ($this->format === null) {
             // if the local format was not setted, the global format is used
             $this->format = self::$globalFormat;
         }
         $symbol = $numberFormatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);
         $number = trim(str_replace($symbol, '', $result));
         $result = str_replace('{symbol}', $symbol, $this->format);
         $result = str_replace('{number}', $number, $result);
     }
     return $result;
 }
Example #22
0
function to_decimals($number, $decimals, $type = \NumberFormatter::DECIMAL)
{
    // ignore empty strings and return
    // NOTE: do not change it to empty otherwise tables will show a 0 with no decimal nor currency symbol
    if (!isset($number)) {
        return $number;
    }
    $config = get_instance()->config;
    $fmt = new \NumberFormatter($config->item('number_locale'), $type);
    $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $config->item($decimals));
    $fmt->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $config->item($decimals));
    if (empty($config->item('thousands_separator'))) {
        $fmt->setAttribute(\NumberFormatter::GROUPING_SEPARATOR_SYMBOL, '');
    }
    $fmt->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, $config->item('currency_symbol'));
    return $fmt->format($number);
}
Example #23
0
 /**
  * Locale-aware number and monetary formatting.
  * Due to issues with the operating system functions on some platforms intl extension is used if available
  *
  *     // In English, "1,200.05"
  *     // In Spanish, "1200,05"
  *     // In Portuguese, "1 200,05"
  *     echo Num::format(1200.05, 2);
  *
  *     // In English, "1,200.05"
  *     // In Spanish, "1.200,05"
  *     // In Portuguese, "1.200.05"
  *     echo Num::format(1200.05, 2, true);
  *
  * @param   float   $number     number to format
  * @param   integer $places     decimal places
  * @param   boolean $monetary   monetary formatting?
  * @return  string
  */
 public static function format($number, $places, $monetary = false)
 {
     if (extension_loaded('intl')) {
         $mode = $monetary ? \NumberFormatter::CURRENCY : \NumberFormatter::DECIMAL;
         $formatter = new \NumberFormatter(\Locale::getDefault(), $mode);
         $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $places);
         $result = $formatter->format($number);
         return $monetary ? str_replace($formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL), '', $result) : $result;
     }
     $info = localeconv();
     if ($monetary) {
         $decimal = $info['mon_decimal_point'];
         $thousands = $info['mon_thousands_sep'];
     } else {
         $decimal = $info['decimal_point'];
         $thousands = $info['thousands_sep'];
     }
     return number_format($number, $places, $decimal, $thousands);
 }
Example #24
0
 /**
  * {@inheritdoc}
  */
 public function format($value, array $options = array())
 {
     if (null === $value) {
         return $options['null_value'];
     }
     if (!is_numeric($value)) {
         throw FormatterException::invalidType($this, $value, 'numeric value');
     }
     $formatter = new \NumberFormatter(\Locale::getDefault(), \NumberFormatter::DECIMAL);
     if (null !== $options['precision']) {
         $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $options['precision']);
         $formatter->setAttribute(\NumberFormatter::ROUNDING_MODE, $options['rounding_mode']);
     }
     $formatter->setAttribute(\NumberFormatter::GROUPING_USED, $options['grouping']);
     $value = $formatter->format($value);
     if (intl_is_failure($formatter->getErrorCode())) {
         throw FormatterException::intlError($this, $formatter->getErrorMessage());
     }
     return $value;
 }
Example #25
0
 private function format()
 {
     $locale = $this->locale === null ? \Locale::getDefault() : $this->locale;
     $numberFormatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
     $result = $numberFormatter->format($this->getValue());
     if ($this->format !== null || self::$globalFormat !== null) {
         // need a special format?
         if ($this->format === null) {
             // if the local format was not setted, the global format is used
             $this->format = self::$globalFormat;
         }
         // remove the parenthesis indicating negative value, it will be placed afterwards
         $result = trim($result, '()');
         $symbol = $numberFormatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);
         $number = trim(str_replace($symbol, '', $result));
         $result = str_replace('{symbol}', $symbol, $this->format);
         $result = str_replace('{number}', $number, $result);
     }
     return $result;
 }
 /**
  * {@inheritdoc}
  */
 public function localize($number, array $options = [])
 {
     if (null === $number || '' === $number) {
         return $number;
     }
     $options = $this->getOptions($options);
     if (isset($options['locale'])) {
         $numberFormatter = new \NumberFormatter($options['locale'], \NumberFormatter::DECIMAL);
         if (isset($options['disable_grouping_separator']) && true === $options['disable_grouping_separator']) {
             $numberFormatter->setSymbol(\NumberFormatter::GROUPING_SEPARATOR_SYMBOL, '');
         }
         if (floor($number) != $number) {
             $numberFormatter->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 2);
             $numberFormatter->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 4);
         }
         return $numberFormatter->format($number);
     }
     $matchesNumber = $this->getMatchesNumber($number);
     if (!isset($matchesNumber['decimal'])) {
         return $number;
     }
     return str_replace(static::DEFAULT_DECIMAL_SEPARATOR, $options['decimal_separator'], $number);
 }
Example #27
0
 public function format($amount)
 {
     $realFormat = str_replace("\$", "¤", $this->format);
     $numFormatter = new \NumberFormatter(null, \NumberFormatter::PATTERN_DECIMAL, $realFormat);
     $numFormatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, $this->symbol);
     $numFormatter->setSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimalSeparator);
     $numFormatter->setSymbol(\NumberFormatter::MONETARY_SEPARATOR_SYMBOL, $this->decimalSeparator);
     $numFormatter->setSymbol(\NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->thousandsSeparator);
     $numFormatter->setSymbol(\NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL, $this->thousandsSeparator);
     // PHP fix: number of decimal digits is forced without pattern analysis
     // when in currency mode (with currency symbol in format)
     if (strpos($realFormat, "¤") !== FALSE) {
         // Count number of 0 after decimal separator
         $parts = explode(".", $realFormat);
         $decimals = 0;
         if (count($parts) == 2) {
             $decimalPart = $parts[1];
             $decimals = count(explode("0", $decimalPart)) - 1;
         }
         $numFormatter->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
     }
     return $numFormatter->format($amount);
 }
Example #28
0
 public function getDisplayedValue($value)
 {
     if ($value !== null && $value !== '') {
         $formatter = new \NumberFormatter($this->locale, $this->style);
         if ($this->precision !== null) {
             $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->precision);
             $formatter->setAttribute(\NumberFormatter::ROUNDING_MODE, $this->roundingMode);
         }
         if ($this->ruleSet !== null) {
             $formatter->setTextAttribute(\NumberFormatter::DEFAULT_RULESET, $this->ruleSet);
         }
         $formatter->setAttribute(\NumberFormatter::GROUPING_USED, $this->grouping);
         if ($this->style === \NumberFormatter::PERCENT && !$this->fractional) {
             $value /= 100;
         }
         if ($this->style === \NumberFormatter::CURRENCY) {
             if ($this->currencyCode === null) {
                 $this->currencyCode = $formatter->getTextAttribute(\NumberFormatter::CURRENCY_CODE);
             }
             if (strlen($this->currencyCode) !== 3) {
                 throw new TransformationFailedException('Your locale definition is not complete, you have to define a language and a country. (.e.g en_US, fr_FR)');
             }
             $value = $formatter->formatCurrency($value, $this->currencyCode);
         } else {
             $value = $formatter->format($value);
         }
         if (intl_is_failure($formatter->getErrorCode())) {
             throw new TransformationFailedException($formatter->getErrorMessage());
         }
         if (key_exists((string) $value, $this->values)) {
             $value = $this->values[$value];
         }
         return $value;
     }
     return '';
 }
 /**
  * format interval (use NumberFormatter if intl extension is found)
  * 
  * @param integer $number
  * @param Zend_Translate $translation
  * @param NumberFormatter|null $numberFormatter
  * @return string
  */
 protected function _formatInterval($number, $translation, $numberFormatter = null)
 {
     if ($numberFormatter === null && extension_loaded('intl')) {
         $locale = new Zend_Locale($translation->getAdapter()->getLocale());
         $numberFormatter = new NumberFormatter((string) $locale, NumberFormatter::ORDINAL);
     }
     $result = $numberFormatter ? $numberFormatter->format($number) : $this->_getIntervalTranslation($number, $translation);
     return $result;
 }
<?php

$number = '1234.56';
// $formatted1 is 1,234.56
$usa = new \NumberFormatter("en-US", NumberFormatter::DEFAULT_STYLE);
$formatted1 = $usa->format($number);
// $formatted2 is 1 234,56
// Note that it's a "non breaking space (\u00A0) between the 1 and the 2
$france = new \NumberFormatter("fr-FR", NumberFormatter::DEFAULT_STYLE);
$formatted2 = $france->format($number);