/** * Filter value * * @param double $value * @return string */ public function filter($value) { $value = floatval($value); $value = Mage::app()->getStore()->roundPrice($this->_rate * $value); //$value = round($value, 2); return $this->_currency->toCurrency($value); }
public function CurrencySymbol() { require_once THIRDPARTY_PATH . "/Zend/Currency.php"; $locale = new Zend_Locale(i18n::get_locale()); $symbol = new Zend_Currency($locale); return $symbol->getSymbol(); }
/** * Filter value * * @param double $value * @return string */ public function filter($value) { $value = Mage::app()->getLocale()->getNumber($value); $value = Mage::app()->getStore()->roundPrice($this->_rate * $value); //$value = round($value, 2); $value = sprintf("%f", $value); return $this->_currency->toCurrency($value); }
/** * Formats a given value * @see library/Bvb/Grid/Formatter/Bvb_Grid_Formatter_FormatterInterface::format() */ public function format($value) { if ($this->_locale === null || !is_numeric($value)) { return $value; } $currency = new Zend_Currency($this->_locale); return $currency->toCurrency($value); }
/** * Retrives pattern with local date format * @return string */ public function getFormat() { $currency = new Zend_Currency(Mage::app()->getStore()->getBaseCurrency()->getCode(), Mage::app()->getLocale()->getLocaleCode()); $format = $currency->toCurrency('0'); $format = preg_replace('/\\d+.\\d+/', '%f', $format); $format = str_replace(' ', '', $format); return $format; }
/** * Format a numeric currency value and return it as a string * * @param int|float $value any value that return true with is_numeric * @param array $options additional options to pass to the currency * constructor * @param string $locale locale value * * @throws InvalidParameterException if the $value parameter is not numeric * @return string the formatted value */ public function currency($value, $options = array(), $locale = null) { if (!is_numeric($value)) { throw new InvalidArgumentException('Numeric argument expected ' . gettype($value) . ' given'); } $options = array_merge($options, array('value' => $value)); $currency = new Zend_Currency($options, $locale); return $currency->toString(); }
private function _getShippingMultiOptions() { $currency = new Zend_Currency(); $shipping = new Storefront_Model_Shipping(); $options = array(0 => 'Please Select'); foreach ($shipping->getShippingOptions() as $key => $value) { $options["{$value}"] = $key . ' - ' . $currency->toCurrency($value); } return $options; }
/** * Convert currency value to another currency. Will throw an exception if value cannot be converted. * * @param $ps_value string Currency value with specifier (Ex. $500, USD 500, ��1200, CAD 750) * @param $ps_to string Specifier of currency to convert value to (Ex. USD, CAD, EUR) * @param $pa_options array Options are: * numericValue = return floating point numeric value only, without currency specifier. Default is false. * * @return string Converted value with currency specifier, unless numericValue option is set. */ public static function convert($ps_value, $ps_to, $pa_options = null) { $va_currency_data = WLPlugCurrencyConversionEuroBank::_loadData(); $ps_to = parent::normalizeCurrencySpecifier($ps_to); if (preg_match("!^([^\\d]+)([\\d\\.\\,]+)\$!", trim($ps_value), $va_matches)) { $vs_decimal_value = (double) $va_matches[2]; $vs_currency_specifier = trim($va_matches[1]); // or 1 } else { if (preg_match("!^([\\d\\.\\,]+)([^\\d]+)\$!", trim($ps_value), $va_matches)) { $vs_decimal_value = (double) $va_matches[1]; $vs_currency_specifier = trim($va_matches[2]); // or 2 } else { if (preg_match("!(^[\\d\\,\\.]+\$)!", trim($ps_value), $va_matches)) { $vs_decimal_value = (double) $va_matches[1]; $vs_currency_specifier = null; // derp } else { throw new Exception(_t('%1 is not a valid currency value; be sure to include a currency symbol', $ps_value)); return false; } } } if (!$vs_currency_specifier) { $o_currency = new Zend_Currency(); $vs_currency_specifier = $o_currency->getShortName(); } $vs_currency_specifier = parent::normalizeCurrencySpecifier($vs_currency_specifier); if (!self::canConvert($vs_currency_specifier, $ps_to)) { throw new Exception(_t('Cannot convert %1 to %2', $vs_currency_specifier, $ps_to)); return false; } $vn_value_in_euros = $vs_decimal_value / $va_currency_data[$vs_currency_specifier]; $vn_converted_value = $vn_value_in_euros * $va_currency_data[$ps_to]; if (caGetOption('numericValue', $pa_options, false)) { return (double) sprintf("%01.2f", $vn_converted_value); } if (Zend_Registry::isRegistered("Zend_Locale")) { $o_locale = Zend_Registry::get('Zend_Locale'); } else { $o_locale = new Zend_Locale('en_US'); } $vs_format = Zend_Locale_Data::getContent($o_locale, 'currencynumber'); // this returns a string like '50,00 ��' for locale de_DE $vs_decimal_with_placeholder = Zend_Locale_Format::toNumber($vn_converted_value, array('locale' => $o_locale, 'number_format' => $vs_format, 'precision' => 2)); // if the currency placeholder is the first character, for instance in en_US locale ($10), insert a space. // this has to be done because we don't print "$10" (which is expected in the locale rules) but "USD 10" ... and that looks nicer with an additional space. if (substr($vs_decimal_with_placeholder, 0, 2) == '��') { // for whatever reason '��' has length 2 $vs_decimal_with_placeholder = str_replace('��', '�� ', $vs_decimal_with_placeholder); } // insert currency which is not locale-dependent in our case return str_replace('��', $ps_to, $vs_decimal_with_placeholder); }
/** * Format Price to locale * * @param $price * @return string */ public static function formatPrice($price) { try { $zCurrency = new \Zend_Currency("de_DE"); //TODO: fix to use Zend_Locale return $zCurrency->toCurrency($price, array('symbol' => Tool::getCurrency()->getSymbol())); } catch (\Exception $ex) { echo $ex; } return $price; }
public function getDefaultCurrencySymbol() { $current_locale = I18n::getCurrentLangCode(); require_once 'Zend/Currency.php'; $current_currency = DEFAULT_CURRENCY; if (!$current_currency) { $current_currency = "USD"; } $currency = new Zend_Currency($current_currency, $current_locale); $currency->getSymbol($current_currency, $current_locale); return $display_name; }
/** * Specific controller action for displaying a particular list of links * for a class * * @return mixed */ public function index() { if (GoogleShoppingFeed::enabled()) { Config::inst()->update('SSViewer', 'set_source_file_comments', false); $this->getResponse()->addHeader('Content-Type', 'application/xml; charset="utf-8"'); $this->getResponse()->addHeader('X-Robots-Tag', 'noindex'); $items = GoogleShoppingFeed::get_items(); $currency = new Zend_Currency(i18n::get_locale()); $this->extend('updateGoogleShoppingFeedItems', $items); return array("SiteConfig" => SiteConfig::current_site_config(), 'Items' => $items, "Currency" => $currency->getShortName()); } else { return new SS_HTTPResponse(_t("GoogleShoppingFeed.PageNotFound", 'Page not found'), 404); } }
/** * returns the value formatet in the current locales currency format * * @return string */ public function Currency($symbol = false) { require_once THIRDPARTY_PATH . "/Zend/Locale/Format.php"; require_once THIRDPARTY_PATH . "/Zend/Currency.php"; if ($this->owner->value) { $locale = new Zend_Locale(i18n::get_locale()); $number = Zend_Locale_Format::toNumber($this->owner->value, array('locale' => $locale)); if ($symbol) { $symbol = new Zend_Currency($locale); $number = $symbol->getSymbol() . " " . $number; } return $number; } }
public function preco($especialidade_id, $simbol = true) { $salao_id = Zend_Auth::getInstance()->getIdentity()->salao_id; $modelEspecialidadePreco = new Model_DbTable_EspecialidadePreco(); $preco = $modelEspecialidadePreco->getPrecoEspecialidadeSalao($especialidade_id, $salao_id); if (!$preco) { return ""; } $zendCurrency = new Zend_Currency(); $options = array(); if (!$simbol) { $options = array('precision' => 2, 'symbol' => ''); } return $zendCurrency->toCurrency($preco->especialidade_preco_preco, $options); }
/** * Creates a currency instance. * * @param CacheInterface $appCache * @param string|array $options Options array or currency short name when string is given * @param string $locale Locale name */ public function __construct(CacheInterface $appCache, $options = null, $locale = null) { // set Zend cache to low level frontend app cache $lowLevelFrontendCache = $appCache->getFrontend()->getLowLevelFrontend(); \Zend_Currency::setCache($lowLevelFrontendCache); parent::__construct($options, $locale); }
/** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. * * @return void */ public function setUp() { $this->clearRegistry(); $this->_cache = Zend_Cache::factory('Core', 'File', array('lifetime' => 120, 'automatic_serialization' => true), array('cache_dir' => dirname(__FILE__) . '/../../_files/')); Zend_Currency::setCache($this->_cache); $this->helper = new Zend_View_Helper_Currency('de_AT'); }
/** * Sets the formating options of the localized currency string * If no parameter is passed, the standard setting of the * actual set locale will be used * * @param array $options (Optional) Options to set * @return Zend_Currency */ public function setFormat(array $options = array()) { if (isset($options['id'])) { $this->id = (int) $options['id']; } return parent::setFormat($options); }
/** * @param mixed $currency */ public function setCurrency($price, $userCurrencyId = null) { $cy = new Application_Model_CurrencyMapper(); $currency_id = $cy->getDefaultCurrency()->id; $code = $cy->find($currency_id)->code; $currency = null; if ($userCurrencyId) { $userCode = $cy->find($userCurrencyId)->code; $currency = new Zend_Currency(array('value' => 1, 'currency' => $userCode, 'display' => Zend_Currency::USE_SHORTNAME, 'position' => Zend_Currency::RIGHT, 'format' => '#0.# ')); $exService = new My_Class_ExchangeService(); $currency->setService($exService); $currency->setValue($price, $code); } else { $currency = new Zend_Currency(array('value' => $price, 'currency' => $code, 'display' => Zend_Currency::USE_SHORTNAME, 'position' => Zend_Currency::RIGHT, 'format' => '#0.# ')); } $this->currency = $currency; }
/** * Output a formatted currency * * @param integer|float $value Currency value to output * @param string|Zend_Locale|Zend_Currency $currency OPTIONAL Currency to use for this call * @return string Formatted currency */ public function currency($value = null, $currency = null) { if ($value === null) { return $this; } if (is_string($currency) || $currency instanceof Zend_Locale) { if (Zend_Locale::isLocale($currency)) { $currency = array('locale' => $currency); } } if (is_string($currency)) { $currency = array('currency' => $currency); } if (is_array($currency)) { return $this->_currency->toCurrency($value, $currency); } return $this->_currency->toCurrency($value); }
/** * @return string */ public function getName($currency = null, $locale = null) { if ($locale === null) { $locale = $this->getLocale(); } if ($currency === null) { $currency = $this->getCurrency(); } return $this->currencyLib->getName($currency, $locale); }
/** * Convenience method * call $this->formatDate() in the view to access * the helper * * @access public * @return string */ public function formatAmount($amount, $currencyIso = NULL) { $formattedAmount = new Zend_Currency(); $formattedAmount->setValue($amount); if (!is_null($currencyIso)) { switch ($currencyIso) { case 'EUR': $locale = 'es_ES'; break; case 'GBP': $locale = 'en_GB'; break; default: $locale = 'en_US'; break; } $formattedAmount->setLocale($locale); } return $formattedAmount; }
function getFromList(&$list) { $current_locale = I18n::getCurrentLangCode(); //require_once('Zend/Locale.php'); $locale = new \Zend_Locale($current_locale); $current_currency = CUBI_DEFAULT_CURRENCY; if (!$current_currency) { $current_currency = "USD"; } //require_once('Zend/Currency.php'); $currency = new \Zend_Currency($current_currency, $current_locale); $currencyList = $currency->getCurrencyList(); foreach ($currencyList as $currency_code => $country) { $display_name = $currency->getName($currency_code, $current_locale); if ($display_name) { array_push($list, array("val" => $currency_code, "txt" => "{$currency_code} - {$display_name}")); } } return $list; }
/** * Parses a Zend_Currency & Zend_Locale into a NostoCurrency object. * * REQUIRES Zend Framework (version 1) to be available. * * @param string $currencyCode the 3-letter ISO 4217 currency code. * @param Zend_Currency $zendCurrency the zend currency object. * @return NostoCurrency the parsed nosto currency object. * * @throws NostoInvalidArgumentException */ public function parseZendCurrencyFormat($currencyCode, Zend_Currency $zendCurrency) { try { $format = Zend_Locale_Data::getContent($zendCurrency->getLocale(), 'currencynumber'); $symbols = Zend_Locale_Data::getList($zendCurrency->getLocale(), 'symbols'); // Remove extra part, e.g. "¤ #,##0.00; (¤ #,##0.00)" => "¤ #,##0.00". if (($pos = strpos($format, ';')) !== false) { $format = substr($format, 0, $pos); } // Check if the currency symbol is before or after the amount. $symbolPosition = strpos(trim($format), '¤') === 0 ? NostoCurrencySymbol::SYMBOL_POS_LEFT : NostoCurrencySymbol::SYMBOL_POS_RIGHT; // Remove all other characters than "0", "#", "." and ",", $format = preg_replace('/[^0\\#\\.,]/', '', $format); // Calculate the decimal precision. $precision = 0; if (($decimalPos = strpos($format, '.')) !== false) { $precision = strlen($format) - (strrpos($format, '.') + 1); } else { $decimalPos = strlen($format); } $decimalFormat = substr($format, $decimalPos); if (($pos = strpos($decimalFormat, '#')) !== false) { $precision = strlen($decimalFormat) - $pos - $precision; } // Calculate the group length. if (strrpos($format, ',') !== false) { $groupLength = $decimalPos - strrpos($format, ',') - 1; } else { $groupLength = strrpos($format, '.'); } // If the symbol is missing for the current locale, use the ISO code. $currencySymbol = $zendCurrency->getSymbol(); if (is_null($currencySymbol)) { $currencySymbol = $currencyCode; } return new NostoCurrency(new NostoCurrencyCode($currencyCode), new NostoCurrencySymbol($currencySymbol, $symbolPosition), new NostoCurrencyFormat($symbols['group'], $groupLength, $symbols['decimal'], $precision)); } catch (Zend_Exception $e) { throw new NostoInvalidArgumentException($e); } }
/** * Gets the number of sharers allowed. * * Method which returns the number of sharers that are permitted * given a specified cover amount. * * @param Zend_Currency $coverAmount * The main cover amount on the TCI+ policy. * * @return integer * Returns the number of sharers allowed on the $coverAmount given. */ public function getNoOfSharersAllowed($coverAmount) { $params = Zend_Registry::get('params'); //Read in the lower contents bands. $bandLower = array(); $bandLower[] = new Zend_Currency(array('value' => $params->sharers->band0->lower, 'precision' => 0)); $bandLower[] = new Zend_Currency(array('value' => $params->sharers->band1->lower, 'precision' => 0)); $bandLower[] = new Zend_Currency(array('value' => $params->sharers->band2->lower, 'precision' => 0)); $bandLower[] = new Zend_Currency(array('value' => $params->sharers->band3->lower, 'precision' => 0)); //Read in the upper contents bands. $bandUpper = array(); $bandUpper[] = new Zend_Currency(array('value' => $params->sharers->band0->upper, 'precision' => 0)); $bandUpper[] = new Zend_Currency(array('value' => $params->sharers->band1->upper, 'precision' => 0)); $bandUpper[] = new Zend_Currency(array('value' => $params->sharers->band2->upper, 'precision' => 0)); $bandUpper[] = new Zend_Currency(array('value' => $params->sharers->band3->upper, 'precision' => 0)); $numberPermitted = array(); $numberPermitted[] = $params->sharers->numberPermitted->band0; $numberPermitted[] = $params->sharers->numberPermitted->band1; $numberPermitted[] = $params->sharers->numberPermitted->band2; $numberPermitted[] = $params->sharers->numberPermitted->band3; //Zero sharers by default until the cover amount is understood. $returnVal = 0; for ($i = 0; $i < count($bandLower); $i++) { $bandFound = false; if ($coverAmount->isMore($bandLower[$i]) && $coverAmount->isLess($bandUpper[$i])) { $bandFound = true; } else { if ($coverAmount->equals($bandLower[$i]) || $coverAmount->equals($bandUpper[$i])) { $bandFound = true; } } if ($bandFound) { $returnVal = $numberPermitted[$i]; break; } } return $returnVal; }
/** * Internal method which calculates the exchanges currency * * @param float|integer|Zend_Currency $value Compares the currency with this value * @param string|Zend_Currency $currency The currency to compare this value from * @return unknown */ protected function _exchangeCurrency($value, $currency) { if ($value instanceof Zend_Currency) { $currency = $value->getShortName(); $value = $value->getValue(); } else { $currency = $this->getShortName($currency, $this->getLocale()); } $rate = 1; if ($currency !== $this->getShortName()) { $service = $this->getService(); if (!$service instanceof Zend_Currency_CurrencyInterface) { require_once 'Zend/Currency/Exception.php'; throw new Zend_Currency_Exception('No exchange service applied'); } $rate = $service->getRate($currency, $this->getShortName()); } $value *= $rate; return $value; }
/** * Identifies if the previous claims will force a referral. * * @param string $refNo * The unique legacy customer reference number. * * @return mixed * Returns an array of referral reasons. If there are no referral reasons, * then will return null. */ protected function _checkPreviousClaims($refNo) { $previousClaimsReferralReasons = array(); if (empty($this->_previousClaimsModel)) { $this->_previousClaimsModel = new Datasource_Insurance_PreviousClaims(); } $previousClaimsArray = $this->_previousClaimsModel->getPreviousClaims($refNo); if (!empty($previousClaimsArray)) { //Tenant has one or more claims. Add the totals together to see if they exceed //the threshold. $claimsTotal = new Zend_Currency(array('value' => 0, 'precision' => 2)); foreach ($previousClaimsArray as $previousClaim) { $claimsTotal->add($previousClaim->getClaimValue()); } //Test against the previous claims threshold $claimsThreshold = new Zend_Currency(array('value' => $params->uw->rt->portfolio->claimsThreshold, 'precision' => 2)); if ($claimsTotal->isMore($claimsThreshold)) { $previousClaimsReferralReasons[] = $params->uw->rr->portfolio->previousClaims; } } //Return the results consistent with this method's contract. if (empty($previousClaimsReferralReasons)) { $returnVal = null; } else { $returnVal = $previousClaimsReferralReasons; } return $returnVal; }
/** * Create Zend_Currency object for current locale * * @param string $currency * @return Zend_Currency */ public function currency($currency) { Varien_Profiler::start('locale/currency'); if (!isset(self::$_currencyCache[$this->getLocaleCode()][$currency])) { try { $currencyObject = new Zend_Currency($currency, $this->getLocale()); } catch (Exception $e) { $currencyObject = new Zend_Currency($this->getCurrency(), $this->getLocale()); $options = array('name' => $currency, 'currency' => $currency, 'symbol' => $currency); $currencyObject->setFormat($options); } self::$_currencyCache[$this->getLocaleCode()][$currency] = $currencyObject; } Varien_Profiler::stop('locale/currency'); return self::$_currencyCache[$this->getLocaleCode()][$currency]; }
?> </th> <th width="80"><?php echo $this->translate('online-shop.back-office.order.order-items'); ?> </th> <th></th> <th width="100"><?php echo $this->translate('online-shop.back-office.order.price.total'); ?> </th> </tr> </thead> <tbody> <?php $totalSum = new Zend_Currency(OnlineShop_Framework_Factory::getInstance()->getEnvironment()->getCurrencyLocale()); foreach ($paginator as $item) { /* @var \OnlineShop\Framework\OrderManager\IOrderListItem $item */ $totalSum->add($item->getTotalPrice()); ?> <tr> <td> <?php $urlDetail = $this->url(['action' => 'detail', 'controller' => 'admin-order', 'module' => 'OnlineShop', 'id' => $item->getOrderId()], null, true); ?> <a href="<?php echo $urlDetail; ?> "><?php echo $item->getOrderNumber(); ?>
/** * Returns default value for a preference * * @param string $ps_pref Preference code * @param array $pa_options No options supported yet * @return mixed Type returned varies by preference */ public function getPreferenceDefault($ps_pref, $pa_options = null) { if (!is_array($va_pref_info = $this->getPreferenceInfo($ps_pref))) { return null; } switch ($va_pref_info["formatType"]) { # --------------------------------- case 'FT_OBJECT_EDITOR_UI': case 'FT_OBJECT_LOT_EDITOR_UI': case 'FT_ENTITY_EDITOR_UI': case 'FT_PLACE_EDITOR_UI': case 'FT_OCCURRENCE_EDITOR_UI': case 'FT_COLLECTION_EDITOR_UI': case 'FT_STORAGE_LOCATION_EDITOR_UI': case 'FT_OBJECT_REPRESENTATION_EDITOR_UI': case 'FT_REPRESENTATION_ANNOTATION_EDITOR_UI': case 'FT_SET_EDITOR_UI': case 'FT_SET_ITEM_EDITOR_UI': case 'FT_LIST_EDITOR_UI': case 'FT_LIST_ITEM_EDITOR_UI': case 'FT_LOAN_EDITOR_UI': case 'FT_MOVEMENT_EDITOR_UI': case 'FT_TOUR_EDITOR_UI': case 'FT_TOUR_STOP_EDITOR_UI': case 'FT_SEARCH_FORM_EDITOR_UI': case 'FT_BUNDLE_DISPLAY_EDITOR_UI': case 'FT_RELATIONSHIP_TYPE_EDITOR_UI': case 'FT_USER_INTERFACE_EDITOR_UI': case 'FT_USER_INTERFACE_SCREEN_EDITOR_UI': case 'FT_IMPORT_EXPORT_MAPPING_EDITOR_UI': case 'FT_IMPORT_EXPORT_MAPPING_GROUP_EDITOR_UI': $vn_type_id = is_array($pa_options) && isset($pa_options['type_id']) && (int) $pa_options['type_id'] ? (int) $pa_options['type_id'] : null; $vn_table_num = $this->_editorPrefFormatTypeToTableNum($va_pref_info["formatType"]); $va_uis = $this->_getUIListByType($vn_table_num); $va_defaults = array(); foreach ($va_uis as $vn_type_id => $va_editor_info) { foreach ($va_editor_info as $vn_ui_id => $va_editor_labels) { $va_defaults[$vn_type_id] = $vn_ui_id; } } return $va_defaults; break; case 'FT_TEXT': if ($va_pref_info['displayType'] == 'DT_CURRENCIES') { // this respects the global UI locale which is set using Zend_Locale $o_currency = new Zend_Currency(); return ($vs_currency_specifier = $o_currency->getShortName()) ? $vs_currency_specifier : "CAD"; } return $va_pref_info["default"] ? $va_pref_info["default"] : null; break; # --------------------------------- # --------------------------------- default: return $va_pref_info["default"] ? $va_pref_info["default"] : null; break; # --------------------------------- } }
public function parseValue($ps_value, $pa_element_info, $pa_options = null) { $ps_value = trim($ps_value); $va_settings = $this->getSettingValuesFromElementArray($pa_element_info, array('minValue', 'maxValue', 'mustNotBeBlank')); if (strlen($ps_value) == 0) { if ((bool) $va_settings['mustNotBeBlank']) { $this->postError(1970, _t('%1 must not be empty', $pa_element_info['displayLabel']), 'CurrencyAttributeValue->parseValue()'); return false; } return null; } // it's either "<something><decimal>" ($1000) or "<decimal><something>" (1000 EUR) or just "<decimal>" with an implicit <something> // either if (preg_match("!^([^\\d]+)([\\d\\.\\,]+)\$!", trim($ps_value), $va_matches)) { $vs_decimal_value = $va_matches[2]; $vs_currency_specifier = trim($va_matches[1]); // or 1 } else { if (preg_match("!^([\\d\\.\\,]+)([^\\d]+)\$!", trim($ps_value), $va_matches)) { $vs_decimal_value = $va_matches[1]; $vs_currency_specifier = trim($va_matches[2]); // or 2 } else { if (preg_match("!(^[\\d\\,\\.]+\$)!", trim($ps_value), $va_matches)) { $vs_decimal_value = $va_matches[1]; $vs_currency_specifier = null; // derp } else { $this->postError(1970, _t('%1 is not a valid currency value; be sure to include a currency symbol', $pa_element_info['displayLabel']), 'CurrencyAttributeValue->parseValue()'); return false; } } } if (!$vs_currency_specifier) { // this respects the global UI locale which is set using Zend_Locale $o_currency = new Zend_Currency(); $vs_currency_specifier = $o_currency->getShortName(); } // get UI locale from registry and convert string to actual php float // based on rules for this locale (e.g. most non-US locations use 10.000,00 as notation) if (Zend_Registry::isRegistered("Zend_Locale")) { $o_locale = Zend_Registry::get('Zend_Locale'); } else { $o_locale = new Zend_Locale('en_US'); } try { $vn_value = Zend_Locale_Format::getNumber($vs_decimal_value, array('locale' => $o_locale, 'precision' => 2)); } catch (Zend_Locale_Exception $e) { $this->postError(1970, _t('%1 does not use a valid decimal notation for your locale', $pa_element_info['displayLabel']), 'CurrencyAttributeValue->parseValue()'); return false; } switch ($vs_currency_specifier) { case '$': $o_config = Configuration::load(); $vs_currency_specifier = ($vs_dollars_are_this = $o_config->get('default_dollar_currency')) ? $vs_dollars_are_this : 'USD'; break; case '¥': $vs_currency_specifier = 'JPY'; break; case '£': $vs_currency_specifier = 'GBP'; break; case '€': $vs_currency_specifier = 'EUR'; break; default: $vs_currency_specifier = strtoupper($vs_currency_specifier); break; } if (strlen($vs_currency_specifier) != 3) { $this->postError(1970, _t('Currency specified for %1 does not appear to be valid', $pa_element_info['displayLabel']), 'CurrencyAttributeValue->parseValue()'); return false; } if ($vn_value < 0) { $this->postError(1970, _t('%1 must not be negative', $pa_element_info['displayLabel']), 'CurrencyAttributeValue->parseValue()'); return false; } if ($vn_value < floatval($va_settings['minValue'])) { // value is too low $this->postError(1970, _t('%1 must be at least %2', $pa_element_info['displayLabel'], $va_settings['minValue']), 'CurrencyAttributeValue->parseValue()'); return false; } if (floatval($va_settings['maxValue']) > 0 && $vn_value > floatval($va_settings['maxValue'])) { // value is too high $this->postError(1970, _t('%1 must be less than %2', $pa_element_info['displayLabel'], $va_settings['maxValue']), 'CurrencyAttributeValue->parseValue()'); return false; } return array('value_longtext1' => $vs_currency_specifier, 'value_decimal1' => $vn_value); }
/** * переводит значение заданного типа в строку * * @param mixed $data значение, которое нужно сконвертировать * @param string $type тип данных ('bool','date') * @param int $precision_default задание точного количества знаков после запятой * @return string полученная строка, представляющая данные */ function type_to_str($data, $type, $precision_default = -1) { switch ($type) { case 'encode': return htmlentities($data, ENT_QUOTES, 'utf-8'); case 'translate': return __($data); case "integer": /** * Локально пустые значения спокойно форматируется зендом в 0, * но на сервере, на orbitscipts.com? после форматирования пустого значение, * оно так и остаётся пустое. Я не знаю почему. */ if (is_null($data) || $data == '') { $data = 0; } $res = Zend_Locale_Format::toInteger($data, array('locale' => get_instance()->locale)); return $res; case "float": $precision = 2; /** * Определние нужной точности для денег */ if ($precision_default < 0) { $vals = explode('.', strval((double) $data)); if (isset($vals[1])) { $len = strlen($vals[1]); if ($len > 3) { $precision = 4; } elseif ($len > 2) { $precision = 3; } } } else { $precision = $precision_default; } return number_format($data, $precision, '.', ''); //return Zend_Locale_Format::toFloat($data, array('locale'=> get_instance()->locale)); //return Zend_Locale_Format::toFloat($data, array('locale'=> get_instance()->locale)); case 'procent': return type_to_str($data, 'float', 2) . ' %'; case "money": //return str_replace('%', type_to_str($data, 'float'), get_format('money')); if (is_null($data)) { $data = 0; } /** * @todo Возможно прийдётся определять тип валюты как-то глобально, * когда понадобится использовать что-нибудь отличное от доллара. */ try { $currency = new Zend_Currency(get_instance()->locale, 'USD'); } catch (Zend_Currency_Exception $e) { $currency = new Zend_Currency(get_instance()->default_locale, 'USD'); } $precision = 2; /** * Определние нужной точности для денег */ $vals = explode('.', strval((double) $data)); if (isset($vals[1])) { $len = strlen($vals[1]); } $currency->setFormat(array('precision' => $precision)); try { $value = trim($currency->toCurrency($data)); /** * проверка preg_matchем нужна потмоу что, например в китайском валюта отображается * как: US$0.00 */ if (get_instance()->locale != 'en_US' && preg_match('|^[0-9,\\.\\$\\s\\xc2\\xa0]+$|', $value, $matches)) { $value = '$' . trim(str_replace('$', '', $value)); } } catch (Exception $e) { $value = '0.00'; } return $value; case "nonzeromoney": if ($data == 0) { return "—"; } return type_to_str($data, "money"); case "mysqldate": $data = mktime(0, 0, 0, substr($data, 5, 2), substr($data, 8, 2), substr($data, 0, 4)); return date(get_date_format(), $data); case "mysqlfloat": //return str_replace(',','.',$data); return number_format($data, 8, '.', ''); case 'databasedate': return date("Y-m-d", $data); case 'databasedatetime': return date("Y-m-d H:i:s", $data); case "date": if ($data == 0 || is_null($data)) { return ''; } return date(get_date_format(), $data); case "datetime": $res = date(get_date_format(), $data) . ' ' . date(get_time_format(), $data); return $res; case "bool": return $data ? "true" : "false"; case 'textcode': $num = (int) ($data ^ 67894523); $text = ''; while ($num) { $text .= chr(ord('a') + $num % 26); $num = (int) ($num / 26); } return $text; case "impressions": if ($data < 1000) { return __('< 1 K'); } if ($data < 5000) { return __('1~5 K'); } if ($data < 10000) { return __('5~10 K'); } if ($data < 50000) { return __('10~50 K'); } if ($data < 100000) { return __('50~100 K'); } else { return __('> 100 K'); } case "clicks": if ($data < 100) { return __('< 100'); } if ($data < 900) { return '~ ' . round($data / 100) * 100; } else { return '~ ' . round($data / 1000) . ' K'; } case "mime": return '=?UTF-8?B?' . base64_encode($data) . '?='; default: return $data; } }