Example #1
0
 public function process($value, array $params = array())
 {
     $locale = localeconv();
     $wrapperTpl = isset($params['wrapperTpl']) ? $params['wrapperTpl'] : null;
     $pointTpl = isset($params['pointTpl']) ? $params['pointTpl'] : null;
     $pointSep = isset($params['pointSep']) ? $params['pointSep'] : '';
     $decimalSep = isset($params['decimalSep']) ? $params['decimalSep'] : $locale['decimal_point'];
     $data = json_decode($value);
     $points = array();
     if (is_object($data) && isset($data->points)) {
         foreach ($data->points as $point) {
             $latitude = number_format($point->lat, 8, $decimalSep, '');
             $longitude = number_format($point->lng, 8, $decimalSep, '');
             if ($pointTpl) {
                 $points[] = $this->modx->getChunk($pointTpl, array('latitude' => $latitude, 'longitude' => $longitude));
             } else {
                 $points[] = $latitude . $longitude;
             }
         }
         $pointsString = implode($pointSep, $points);
         if ($wrapperTpl) {
             $output = $this->modx->getChunk($wrapperTpl, array('points' => $pointsString));
         } else {
             $output = $pointsString;
         }
         return $output;
     }
 }
Example #2
0
 /**
  * {@inheritdoc}
  *
  * @param  \Phalcon\Mvc\EntityInterface $record
  * @return boolean
  * @throws \Phalcon\Mvc\Model\Exception
  */
 public function validate(EntityInterface $record)
 {
     $field = $this->getOption('field');
     if (false === is_string($field)) {
         throw new Exception('Field name must be a string');
     }
     $value = $record->readAttribute($field);
     if (true === $this->isSetOption('allowEmpty') && empty($value)) {
         return true;
     }
     if (false === $this->isSetOption('places')) {
         throw new Exception('A number of decimal places must be set');
     }
     if ($this->isSetOption('digits')) {
         // Specific number of digits
         $digits = '{' . (int) $this->getOption('digits') . '}';
     } else {
         // Any number of digits
         $digits = '+';
     }
     if ($this->isSetOption('point')) {
         $decimal = $this->getOption('point');
     } else {
         // Get the decimal point for the current locale
         list($decimal) = array_values(localeconv());
     }
     $result = (bool) preg_match(sprintf('#^[+-]?[0-9]%s%s[0-9]{%d}$#', $digits, preg_quote($decimal), $this->getOption('places')), $value);
     if (!$result) {
         // Check if the developer has defined a custom message
         $message = $this->getOption('message') ?: sprintf('%s must contain valid decimal value', $field);
         $this->appendMessage($message, $field, 'Decimal');
         return false;
     }
     return true;
 }
Example #3
0
 /**
  * @param bool $reload
  * @return array
  */
 public function getLocaleParams($reload = false)
 {
     if (null === $this->localeParams || $reload) {
         $this->localeParams = localeconv();
     }
     return $this->localeParams;
 }
Example #4
0
 /**
  * @return FormatterInterface
  */
 private function getDefaultFormatter()
 {
     $locale = localeconv();
     $formatter = new StandardFormatter();
     $formatter->setDecimalSeperator($locale['decimal_point']);
     return $formatter;
 }
 function Currency_USD()
 {
     $this->lang = "English [en]";
     if (setlocale(LC_MONETARY, 'en_US') !== false && setlocale(LC_NUMERIC, 'en_US') !== false) {
         $this->locale = localeconv();
     }
 }
Example #6
0
 /**
  * Windows-compatible equivalent to built-in money_format function.
  *
  * @param string $number Number to format.
  *
  * @return string
  */
 public static function windowsSafeMoneyFormat($number)
 {
     // '' or NULL gets the locale values from environment variables
     setlocale(LC_ALL, '');
     $locale = localeconv();
     extract($locale);
     // Windows doesn't support UTF-8 encoding in setlocale, so we'll have to
     // convert the currency symbol manually:
     $currency_symbol = self::safeMoneyFormatMakeUTF8($currency_symbol);
     // How is the amount signed?
     // Positive
     if ($number > 0) {
         $sign = $positive_sign;
         $sign_posn = $p_sign_posn;
         $sep_by_space = $p_sep_by_space;
         $cs_precedes = $p_cs_precedes;
     } else {
         // Negative
         $sign = $negative_sign;
         $sign_posn = $n_sign_posn;
         $sep_by_space = $n_sep_by_space;
         $cs_precedes = $n_cs_precedes;
     }
     // Format the absolute value of the number
     $m = number_format(abs($number), $frac_digits, $mon_decimal_point, $mon_thousands_sep);
     // Spaces between the number and symbol?
     if ($sep_by_space) {
         $space = ' ';
     } else {
         $space = '';
     }
     if ($cs_precedes) {
         $m = $currency_symbol . $space . $m;
     } else {
         $m = $m . $space . $currency_symbol;
     }
     // HTML spaces
     $m = str_replace(' ', ' ', $m);
     // Add symbol
     switch ($sign_posn) {
         case 0:
             $m = "({$m})";
             break;
         case 1:
             $m = $sign . $m;
             break;
         case 2:
             $m = $m . $sign;
             break;
         case 3:
             $m = $sign . $m;
             break;
         case 4:
             $m = $m . $sign;
             break;
         default:
             $m = "{$m} [error sign_posn = {$sign_posn} !]";
     }
     return $m;
 }
Example #7
0
 /**
  * Defined by Zend_Validate_Interface
  *
  * Returns true if and only if $value is a valid integer
  *
  * @param  string|integer $value
  * @return boolean
  */
 public function isValid($value)
 {
     if (!is_string($value) && !is_int($value) && !is_float($value)) {
         $this->error(self::INVALID);
         return false;
     }
     if (is_int($value)) {
         return true;
     }
     $this->setValue($value);
     if ($this->locale === null) {
         $locale = localeconv();
         $valueFiltered = str_replace($locale['decimal_point'], '.', $value);
         $valueFiltered = str_replace($locale['thousands_sep'], '', $valueFiltered);
         if (strval(intval($valueFiltered)) != $valueFiltered) {
             $this->error(self::NOT_INT);
             return false;
         }
     } else {
         try {
             if (!Zend_Locale_Format::isInteger($value, ['locale' => $this->locale])) {
                 $this->error(self::NOT_INT);
                 return false;
             }
         } catch (Zend_Locale_Exception $e) {
             $this->error(self::NOT_INT);
             return false;
         }
     }
     return true;
 }
Example #8
0
 /**
  * Checks whether a string is a valid number with optional prefix ~, + or -.
  * Allow only EN . delimiter
  * 
  * @param   string  $str    input string
  * @return  boolean
  */
 public static function numeric_variable($str)
 {
     // Get the decimal point for the current locale
     list($decimal) = array_values(localeconv());
     // A lookahead is used to make sure the string contains at least one digit (before or after the decimal point)
     return (bool) preg_match('/^[~\\+-]?\\d*\\.?\\d*$/', (string) $str);
 }
Example #9
0
 /**
  * {@inheritdoc}
  *
  * @param Validation $validation
  * @param string $attribute
  *
  * @return bool
  * @throws Exception
  */
 public function validate(Validation $validation, $attribute)
 {
     $value = $validation->getValue($attribute);
     $field = $this->getOption('label');
     if (empty($field)) {
         $validation->getLabel($attribute);
     }
     if (false === $this->hasOption('places')) {
         throw new Exception('A number of decimal places must be set');
     }
     if ($this->hasOption('digits')) {
         // Specific number of digits
         $digits = '{' . (int) $this->getOption('digits') . '}';
     } else {
         // Any number of digits
         $digits = '+';
     }
     if ($this->hasOption('point')) {
         $decimal = $this->getOption('point');
     } else {
         // Get the decimal point for the current locale
         list($decimal) = array_values(localeconv());
     }
     $result = (bool) preg_match(sprintf('#^[+-]?[0-9]%s%s[0-9]{%d}$#', $digits, preg_quote($decimal), $this->getOption('places')), $value);
     if (!$result) {
         $message = $this->getOption('message');
         $replacePairs = [':field' => $field];
         if (empty($message)) {
             $message = ':field must contain valid decimal value';
         }
         $validation->appendMessage(new Message(strtr($message, $replacePairs), $attribute, 'Decimal'));
         return false;
     }
     return true;
 }
function ParseFloat($floatString)
{
    $LocaleInfo = localeconv();
    $floatString = str_replace(".", "", $floatString);
    $floatString = str_replace(",", ".", $floatString);
    return floatval($floatString);
}
Example #11
0
 /**
  * Adjust configs like: $Model->Behaviors-attach('Tools.DecimalInput', array('fields'=>array('xyz')))
  * leave fields empty to auto-detect all float inputs
  *
  * @return void
  */
 public function setup(Model $Model, $config = array())
 {
     $this->settings[$Model->alias] = $this->_defaultConfig;
     if (!empty($config['strict'])) {
         $this->settings[$Model->alias]['transform']['.'] = '#';
     }
     if ($this->settings[$Model->alias]['localeconv'] || !empty($config['localeconv'])) {
         // use locale settings
         $conv = localeconv();
         $loc = array('decimals' => $conv['decimal_point'], 'thousands' => $conv['thousands_sep']);
     } elseif ($configure = Configure::read('Localization')) {
         // Use configure settings
         $loc = (array) $configure;
     }
     if (!empty($loc)) {
         $this->settings[$Model->alias]['transform'] = array($loc['thousands'] => $this->settings[$Model->alias]['transform']['.'], $loc['decimals'] => $this->settings[$Model->alias]['transform'][',']);
     }
     $this->settings[$Model->alias] = $config + $this->settings[$Model->alias];
     $numberFields = array();
     $schema = $Model->schema();
     foreach ($schema as $key => $values) {
         if (isset($values['type']) && !in_array($key, $this->settings[$Model->alias]['fields']) && in_array($values['type'], $this->settings[$Model->alias]['observedTypes'])) {
             array_push($numberFields, $key);
         }
     }
     $this->settings[$Model->alias]['fields'] = array_merge($this->settings[$Model->alias]['fields'], $numberFields);
 }
Example #12
0
 public function __construct($locale, $style, $format)
 {
     $lsave = setlocale(LC_ALL, "0");
     $this->def_first_group = 3;
     $this->decimal_sep = '.';
     $this->group_sep = ',';
     $this->exponent_string = "E";
     $this->negative_prefix = "-";
     $this->positive_prefix = "+";
     $loc = setlocale(LC_ALL, $locale);
     if ($loc) {
         $info = localeconv();
         $this->decimal_sep = $info['decimal_point'];
         $this->group_sep = $info['thousands_sep'];
         // $this->negative_prefix = $info['negative_sign'];
         // $this->positive_prefix = $info['positive_sign'];
         setlocale(LC_ALL, $lsave);
     }
     $fmts = explode(";", $format);
     if (!isset($fmts[1])) {
         $fmts[1] = $this->negative_prefix . $fmts[0];
     }
     $neg = $this->parsefmt($fmts[1]);
     $this->pos_format = $this->parsefmt($fmts[0]);
     $neg2 = $this->pos_format;
     $neg2[0] = $neg[0];
     $neg2[3] = $neg[3];
     $this->neg_format = $neg2;
     // print_r($this);
 }
Example #13
0
/**
 * wpcf_field_number_validation_fix
 *
 * Fix JS validation for field:numeric. Allow comma validation 
 */
function wpcf_field_number_validation_fix()
{
    $locale = localeconv();
    if ($locale['decimal_point'] != '.') {
        wp_enqueue_script('wpcf-numeric', WPCF_EMBEDDED_RES_RELPATH . '/js/numeric_fix.js', array('jquery'), WPCF_VERSION);
    }
}
Example #14
0
 public static function Sub($op1, $op2, $op3 = null)
 {
     print "\nSUB";
     print "\nLocale:" . setlocale(LC_ALL, 0);
     print "\nConv:";
     print_r(localeconv());
     print "\nOP1:{$op1}\nOP2:{$op2}\nOP3:{$op3}";
     if (empty($op1)) {
         $op1 = 0;
     }
     self::localize($op1);
     self::localize($op2);
     print "\nLO1:{$op1}\nLO2:{$op2}";
     $result = $op1 - $op2;
     print "\nRES:{$result}";
     print "\nSTR:" . (string) ($result + $op2);
     if ($result === INF or (string) ($result + $op2) != (string) $op1) {
         require_once 'Zend/Locale/Math/Exception.php';
         throw new Zend_Locale_Math_Exception("subtraction overflow: {$op1} - {$op2} != {$result}", $op1, $op2, $result);
     }
     if ($op3 === null) {
         $op3 = Zend_Locale_Math_PhpMath::$_scale;
     }
     return self::round($result, $op3);
 }
Example #15
0
 /**
 		Return ICU-formatted string
 			@return string
 			@param $str string
 			@param $args mixed
 			@public
 	**/
 static function format($str, $args)
 {
     // Format string according to locale rules
     if (extension_loaded('intl')) {
         return msgfmt_format_message(Locale::getDefault(), $str, is_array($args) ? $args : array($args));
     }
     $info = localeconv();
     return preg_replace_callback('/{(\\d+)(?:,(\\w+)(?:,(\\w+))?)?}/', function ($expr) use($args, $info) {
         $arg = $args[$expr[1]];
         if (!isset($expr[2])) {
             return $arg;
         }
         if ($expr[2] == 'number') {
             if (isset($expr[3])) {
                 switch ($expr[3]) {
                     case 'integer':
                         return number_format($arg, 0, $info['decimal_point'], $info['thousands_sep']);
                     case 'currency':
                         return $info['currency_symbol'] . ($info['p_sep_by_space'] ? ' ' : '') . number_format($arg, $info['frac_digits'], $info['mon_decimal_point'], $info['mon_thousands_sep']);
                 }
             } else {
                 return sprintf('%f', $arg);
             }
         } elseif ($expr[2] == 'date') {
             return strftime('%x', $arg);
         } else {
             return $arg;
         }
     }, $str);
 }
Example #16
0
 /**
  * Get the locale info returned by localeconv(), but cache it, to
  * avoid repeated calls.
  *
  * @return array  The results of localeconv().
  */
 public static function getLocaleInfo()
 {
     if (!isset(self::$_cache['lc_info'])) {
         self::$_cache['lc_info'] = localeconv();
     }
     return self::$_cache['lc_info'];
 }
 public function testGetCurrencyCode()
 {
     $localeconv = localeconv();
     $expectedResult = !empty($localeconv['currency_symbol']) ? $localeconv['currency_symbol'] : '$';
     $result = call_user_func(array('PHPExcel_Shared_String', 'getCurrencyCode'));
     $this->assertEquals($expectedResult, $result);
 }
Example #18
0
 static function number2db($value)
 {
     $larr = localeconv();
     $search = array($larr['decimal_point'], $larr['mon_decimal_point'], $larr['thousands_sep'], $larr['mon_thousands_sep'], $larr['currency_symbol'], $larr['int_curr_symbol']);
     $replace = array('.', '.', '', '', '', '');
     return str_replace($search, $replace, $value);
 }
Example #19
0
 function format_Number($number, $decimal = 0)
 {
     // Getting localized numeric formating information
     $locale = localeconv();
     // Return formated number
     return number_format($number, $decimal, $locale['decimal_point'], $locale['thousands_sep']);
 }
Example #20
0
 /**
  * convert a money amount (represented by a float or string (based on locale) ie.: R$ 5,00) to cents (represented by an int).
  *
  * @param float $amount
  *
  * @throws \UnexpectedValueException
  *
  * @return int
  */
 public static function toCents($amount)
 {
     /*
      * There's probably a better way, but this is what i could come up with
      * to avoid rounding errors
      * todo: search for a better way
      */
     if (!is_float($amount)) {
         $type = gettype($amount);
         throw new \UnexpectedValueException("Needs a float! not {$type}");
     }
     //handle locales
     $locale = localeconv();
     $amount = str_replace($locale['mon_thousands_sep'], '', $amount);
     $amount = str_replace($locale['mon_decimal_point'], '.', $amount);
     $amount = str_replace($locale['decimal_point'], '.', $amount);
     $parts = explode('.', "{$amount}");
     // handle the case where $amount has a .0 fraction part
     if (count($parts) == 1) {
         $parts[] = '00';
     }
     list($whole, $fraction) = $parts;
     /*
      * since the documentation only mentions decimals with a precision of two
      * and doesn't specify any rounding method i'm truncating the number
      *
      * the str_pad is to handle the case where $amount is, for example, 6.9
      */
     $fraction = str_pad(substr($fraction, 0, 2), 2, '0');
     $whole = (int) $whole * 100;
     $fraction = (int) $fraction;
     return $whole + $fraction;
 }
Example #21
0
 protected function stats($email = false, $limit = 200)
 {
     $b = $this->getBayesStats();
     if ($email) {
         $b->extra_where = ' AND word like \'@%\'';
     }
     $inf = array();
     list($totalspam, $totalham) = $b->getTotalPosts();
     $inf['total'] = array('spam' => $totalspam, 'ham' => $totalham);
     $inf['totalwords'] = 999999;
     //$b->getTotalWords();
     $inf['recentham'] = $this->postproc($b->getRecentlyAddedHams($limit), $totalspam, $totalham);
     $inf['recentspam'] = $this->postproc(array_values(array_reverse($b->getRecentlyAddedSpams($limit))), $totalspam, $totalham);
     $inf['recentmod'] = $this->postproc($b->getRecentlyModdedWords($limit), $totalspam, $totalham);
     $inf['spammiest'] = $this->postproc($b->getSpammiestWords($limit, $totalspam, $totalham), $totalspam, $totalham);
     $inf['hammiest'] = $this->postproc($b->getHammiestWords($limit, $totalspam, $totalham), $totalspam, $totalham);
     $inf['useless'] = $this->postproc($b->getUselessWords($limit, $totalspam, $totalham), $totalspam, $totalham);
     $inf['strongest'] = $this->postproc($b->getStrongestWords($limit, $totalspam, $totalham), $totalspam, $totalham);
     $inf['oldest'] = $this->postproc($b->getOldestWords($limit), $totalspam, $totalham);
     $inf['pagename'] = $this->prefix == 'bayes' ? 'bayesinfo' : 'bayeslinks';
     $inf['page_template'] = 'bayesinfo';
     $inf['title'] = 'Words for ' . $this->prefix . ($email ? ' (emails only)' : '');
     $locale = localeconv();
     if (!$locale['thousands_sep']) {
         $locale['thousands_sep'] = ',';
     }
     $inf['totalwordsf'] = number_format($inf['totalwords'], 0, $locale['decimal_point'], $locale['thousands_sep']);
     $totalf = number_format($totalspam + $totalham, 0, $locale['decimal_point'], $locale['thousands_sep']);
     $inf['totalspamf'] = number_format($inf['total']['spam'], 0, $locale['decimal_point'], $locale['thousands_sep']);
     return $inf;
 }
Example #22
0
 /**
  * Test string with thousands separator
  *
  */
 public function testStringWithThousandsSeparator()
 {
     $locale = localeconv();
     $string = "1{$locale['thousands_sep']}300";
     $this->assertSame((double) 1300, $this->_filter->filter($string));
     $string = "1{$locale['thousands_sep']}300.54";
     $this->assertSame((double) 1300.54, $this->_filter->filter($string));
 }
function smarty_modifier_money_format($string, $places = 2)
{
    $env = localeconv();
    if ($env['int_curr_symbol'] != 'USD') {
        setlocale(LC_MONETARY, 'en_US');
    }
    return money_format("%.{$places}n", $string);
}
Example #24
0
 /**
  * Formats a number according to the current locale.
  *
  * @param   float
  * @param   int|boolean number of fractional digits or TRUE to use the locale default
  * @return  string
  */
 public static function number($number, $decimals = 0)
 {
     $locale = localeconv();
     if ($decimals === TRUE) {
         return number_format($number, $locale['frac_digits'], $locale['decimal_point'], $locale['thousands_sep']);
     }
     return number_format($number, $decimals, $locale['decimal_point'], $locale['thousands_sep']);
 }
Example #25
0
 /**
  * Check if $value is valid. If it is not valid, needs to add an error
  * to result.
  *
  * @param mixed $value
  * @return void
  */
 public function isValid($value)
 {
     $locale = localeconv();
     $valueFiltered = str_replace(array($locale['thousands_sep'], $locale['mon_thousands_sep'], $locale['decimal_point'], $locale['mon_decimal_point']), array('', '', '.', '.'), $value);
     if ($value != strval(floatval($valueFiltered))) {
         $this->addError($this->renderMessage($this->options['errorMessage'][0], $this->options['errorMessage'][1], 'error'), 1442002070);
     }
 }
 function __construct()
 {
     $this->useMbstring = setLocaleAsBrowser(LC_ALL);
     $locInfo = localeconv();
     $this->decimalMark = $locInfo['mon_decimal_point'];
     $this->thSepMark = $locInfo['mon_thousands_sep'];
     $this->currencyMark = $locInfo['currency_symbol'];
 }
Example #27
0
 static function number_format($number)
 {
     global $language_number_format_locale;
     if (!isset($language_number_format_locale)) {
         $language_number_format_locale = localeconv();
     }
     return number_format($number, $language_number_format_locale['frac_digits'], $language_number_format_locale['decimal_point'], $language_number_format_locale['thousands_sep']);
 }
Example #28
0
function ParseFloat($floatString)
{
    // use comma for thousands until local info is property used
    $LocaleInfo = localeconv();
    $floatString = str_replace(",", "", $floatString);
    $floatString = str_replace($LocaleInfo["decimal_point"], ".", $floatString);
    return floatval($floatString);
}
 public static function getDollarSign()
 {
     $info = localeconv();
     if (!empty($info['currency_symbol'])) {
         return $info['currency_symbol'];
     } else {
         return '$';
     }
 }
Example #30
0
 /**
  * Returns a prettified string representation of a number. The result will have
  * thousands separators and a decimal point specific to the current locale, eg,
  * `'1,000,000.05'` or `'1.000.000,05'`.
  *
  * @param number $value
  * @return string
  * @api
  */
 public function getPrettyNumber($value, $precision = 0)
 {
     if ($this->decimalPoint === null) {
         $locale = localeconv();
         $this->decimalPoint = $locale['decimal_point'];
         $this->thousandsSeparator = $locale['thousands_sep'];
     }
     return number_format($value, $precision, $this->decimalPoint, $this->thousandsSeparator);
 }