Previous Next

How to work with currencies

To use Zend_Currency within the own application just create an instance of it without any parameter. This will create an instance of Zend_Currency with the actual locale, and defines the currency which has to be used for this locale.

Example #1 Creating an instance of Zend_Currency from the actual locale

Expect you have 'en_US' set as actual locale through the users or your environment. By using no parameter while creating the instance you say Zend_Currency to use the actual currency from the locale 'en_US'. This leads to an instance with US Dollar set as actual currency with the formatting rules from 'en_US'.





    

Note:

Be aware, that if your system has no default locale, or if the locale of your system can not be detected automatically, Zend_Currency will throw an exception. If you have this behaviour you should set the locale you manually.

Of course, depending on your needs, several parameters can be given at creation. Each of this parameters is optional and can be suppressed. Even the order of the parameters can be switched. The meaning of each parameter is described in this list:

  • currency:

    A locale can include several currencies. Therefor the first parameter 'currency' can define which currency should be used by giving the short name or full name of that currency. If that currency in not known in any locale an exception will be thrown. Currency short names are always 3 lettered and written uppercase. Well known currency shortnames are for example USD or EUR. For a list of all known currencies see the informational methods of Zend_Currency.

  • locale:

    The third parameter 'locale' defines which locale should be used for formatting the currency. The given locale will also be used to get the standard script and currency of this currency if these parameters are not given.

    Note:

    Note that Zend_Currency only accepts locales which include a region. This means that all given locale which only include the language will throw an exception. For example the locale en will throw an exception whereas the locale en_US will return USD as currency.

Example #2 Other examples for creating an instance of Zend_Currency




    

So you can supress any of these parameters if you want to use the default ones. This has no negative effect on handling the currencies. It can be useful f.e. if you don't know the default currency for a region.

Note:

For many countries there are several known currencies. One currency will actually be used and maybe several ancient currencies. If the 'currency' parameter is suppressed the actual currency will be used. The region 'de' for example knows the currencies 'EUR' and 'DEM'... 'EUR' is the actual one and will be used if the parameter is suppressed.

Create output from an currency

To get an existing value converted to a currency formatted output the method toCurrency() can be used. It takes a value which should be converted. The value itself can be any normalized number.

If you have a localized number you will have to convert it first to an normalized number with Zend_Locale_Format::getNumber(). Afterwards it can be used with toCurrency() to create an currency output.

toCurrency(array $options) accepts an array with options which can be used to temporary set another format or currency representation. For details about which options can be used see Changing the format of a currency.

Example #3 Creating output for an currency

toCurrency(1000);

// prints '$ 1.000,00'
echo $currency->toCurrency(1000, array('format' => 'de_AT'));

// prints '$ ١٬٠٠٠٫٠٠'
echo $currency->toCurrency(1000, array('script' => 'Arab'));

Changing the format of a currency

The format which is used by creation of a Zend_Currency instance is of course the standard format. But sometimes it is necessary to change this format for own purposes.

The format of an currency output includes the following parts:

  • Currency symbol, shortname or name:

    The symbol of the currency is normally displayed within an currency output. It can be suppressed when needed or even overwritten.

  • Currency position:

    The position of the currency sign is normally automatically defined by the locale. It can be changed if necessary.

  • Script:

    The script which shall be used to display digits. Detailed information about scripts and their usage can be found in the documentation of Zend_Locale in supported number scripts.

  • Number formatting:

    The amount of currency (formally known as value of money) is formatted by the usage of formatting rules within the locale. For example is in English the ',' sign used as separator for thousands, and in German the '.' sign.

So if you are in need to change the format, you can use the setFormat() method. It takes an array which includes all options which you want to change. The options array supports the following settings:

  • position: Defines the position at which the currency description should be displayed. The supported position can be found in this table.

  • script: Defined which script has to be used for displaying digits. The default script for most locales is 'Latn', which includes the digits 0 to 9. Also other scripts like 'Arab' (Arabian) can be used. All supported scripts can be found in this table.

  • format: Defines which locale has to be used for displaying numbers. This number-format includes for example the thousand separator. If no format is set the locale from the Zend_Currency object will be used.

  • display: Defines which part of the currency has to be used for displaying the currency representation. There are 4 representations which can be used and which are all described in this table.

  • precision: Defines the precision which has to be used for the currency representation. The default value is 2.

  • name: Defines the full currency name which has to be displayed. This option overwrites any currency name which is set through the creation of Zend_Currency.

  • currency: Defines the international abbreviation which has to be displayed. This option overwrites any abbreviation which is set through the creation of Zend_Currency.

  • symbol: Defines the currency symbol which has to be displayed. This option overwrites any symbol which is set through the creation of Zend_Currency.

Constants for the selecting the currency description
constant description
NO_SYMBOL Do not display any currency representation
USE_SYMBOL Display the currency symbol
USE_SHORTNAME Display the 3 lettered international currency abbreviation
USE_NAME Display the full currency name
Constants for the selecting the currency position
constant description
STANDARD Set the standard position as defined within the locale
RIGHT Display the currency representation at the right side of the value
LEFT Display the currency representation at the left side of the value

Example #4 Changing the displayed format of a currency

toCurrency(1000);

$currency->setFormat('display' => Zend_Currency::USE_NAME, 'position' => Zend_Currency::RIGHT);
// prints '1.000,00 US Dollar'
echo $currency->toCurrency(1000);

$currency->setFormat('name' => 'American Dollar');
// prints '1.000,00 American Dollar'
echo $currency->toCurrency(1000);

Informational methods for Zend_Currency

Of course, Zend_Currency supports also methods to get informations about any existing and many ancient currencies from Zend_Locale. The supported methods are:

  • getSymbol():

    Returns the known sign of the actual currency or a given currency. For example $ for the US Dollar within the locale 'en_US.

  • getShortName():

    Returns the abbreviation of the actual currency or a given currency. For example USD for the US Dollar within the locale 'en_US.

  • getName():

    Returns the full name of the actual currency of a given currency. For example US Dollar for the US Dollar within the locale 'en_US.

  • getRegionList():

    Returns a list of regions where the actual currency or a given one is known to be used. It is possible that a currency is used within several regions therefor the return value is always an array.

  • getCurrencyList():

    Returns a list of currencies which are known to be used in the given region.

The function getSymbol(), getShortName() and getName() accept two optional parameters. If no parameter is given the expected data will be returned from the actual set currency. The first parameter takes the shortname of a currency. Short names are always three lettered, for example EUR for euro or USD for US Dollar. The second parameter defines from which locale the data should be read. If no locale is given, the actual set locale is used.

Example #5 Getting informations from currencies

getSymbol();

// prints 'EUR'
echo $currency->getShortName('EUR');

// prints 'Österreichische Schilling'
echo $currency->getName('ATS', 'de_AT');

// returns an array with all regions where USD is used
print_r($currency->getRegionList();

// returns an array with all currencies which were ever used in this region
print_r($currency->getCurrencyList('de_AT');

Settings new default values

The method setLocale allows to set a new locale for Zend_Currency. When calling this function also all default values for the currency will be overwritten. This includes currency name, abbreviation and symbol.

Example #6 Setting a new locale

toCurrency(1000);

// get the currency for AT
$currency->setLocale('de_AT');
print $currency->toCurrency(1000);

Speed up Zend_Currency

The work of Zend_Currency can be speed up by the usage of Zend_Cache. By using the static method Zend_Currency::setCache($cache) which accepts one option, an Zend_Cache adapter. When you set it, the localization data of the methods from Zend_Currency are cached. For convenience there is also static method Zend_Currency::getCache().

Example #7 Caching currencies

 120, 'automatic_serialization' => true),
             array('cache_dir' => dirname(__FILE__) . '/_files/'));
Zend_Currency::setCache($cache);
Previous Next
Introduction to Zend Framework
Présentation
Installation
Zend_Acl
Introduction
Affiner les Contrôles d'Accès
Utilisation avancée
Zend_Auth
Introduction
Authentification avec une table de base de données
Authentification "Digest"
Adaptateur d'authentification HTTP
LDAP Authentication
Authentification OpenID
Zend_Cache
Introduction
La théorie du cache
Les frontends Zend_Cache
Les backends Zend_Cache
Zend_Captcha
Introduction
Captcha Operation
Captcha Adapters
Zend_Config
Introduction
Point de vue théorique
Zend_Config_Ini
Zend_Config_Xml
Zend_Console_Getopt
Introduction à Getopt
Déclarer les règles Getopt
Extraire les options et les arguments
Configurer Zend_Console_Getopt
Zend_Controller
Zend_Controller - Démarrage rapide
Fondations de Zend_Controller
Le contrôleur frontal (Front Controller)
L'objet Requête
Routeur Standard : Zend_Controller_Router_Rewrite
Le dispatcheur
Contrôleurs d'action
Aides d'action (Helper)
Objet de réponse
Plugins
Utilisation de conventions de dossiers modulaires
Exceptions avec MVC
Migrer depuis des versions précédentes
Zend_Currency
Introduction à Zend_Currency
How to work with currencies
Migrer depuis des versions antérieures
Zend_Date
Introduction
Point de vue théorique
Méthodes de base
Zend_Date API Overview
Créer des dates
Constants for General Date Functions
Exemples concrets
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Relations Zend_Db_Table
Zend_Debug
Afficher des informations
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Les aides de vues Dojo
Les éléments de formulaire et les décorateurs Dojo
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Utiliser les exceptions
Zend_Feed
Introduction
Importer des flux
Obtenir des flux à partir de pages Web
Consommer un flux RSS
Consommer un flux Atom
Consommer une entrée Atom particulière
Modifier la structure du flux ou des entrées
Classes personnalisées pour les flux et entrées
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Zend_Filter
Introduction
Classes de filtre standards
Chaînes de filtrage
Écriture de filtres
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction à Gdata
Authentification par procédé AuthSub
Authentification avec ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Utiliser l'API YouTube
Utilisation des albums Web Picasa
Attraper les exceptions Gdata
Zend_Http
Zend_Http_Client - Introduction
Zend_Http_Client - Utilisation avancée
Zend_Http_Client - Adaptateurs de connexion
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Utilisation de base
Objets JSON
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout - Démarrage rapide
Zend_Layout options de configuration
Zend_Layout, utilisation avancée
Zend_Ldap
Introduction
Zend_Loader
Charger les fichiers et les classes dynamiquement
Chargeur de Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported Languages for Locales
Supported Regions for Locales
Zend_Log
Présentation
Rédacteurs (Writers)
Formateurs (mise en forme)
Filtres
Zend_Mail
Introduction
Envoyer des emails en utilisant SMTP
Envoyer plusieurs emails par connexion SMTP
Utiliser différents transports
Email HTML
Fichiers joints
Ajouter des destinataires
Contrôler les limites MIME
Entêtes additionnelles
Jeux de caractères
Encodage
Authentification SMTP
Sécuriser les transports SMTP
Lire des emails
Zend_Measure
Introduction
Création d'une mesure
Récupérer des mesures
Manipuler des mesures
Types de mesures
Zend_Memory
Présentation
Manager de mémoire
Objet mémoire
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction.
Créer et charger des documents PDF
Sauvegarder les changement dans un document PDF
Les pages d'un document
Dessiner
Informations du document et métadonnées.
Exemple d'utilisation du module Zend_Pdf
Zend_Registry
Utiliser le registre
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Yahoo
Zend_Session
Introduction
Usage basique
Utilisation avancée
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery. Introduction
Class autodiscovering.
Functions autodiscovering.
Autodiscovering. Datatypes.
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_TimeSync
Introduction
Utiliser Zend_TimeSync
Zend_Translate
Introduction
Adaptateurs pour Zend_Translate
Utiliser les adaptateurs de traduction
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Classes de validation standard
Chaînes de validation
Ecrire des validateurs
Zend_Version
Lire la version du Zend Framework
Zend_View
Introduction
Scripts de contrôleur
Scripts de vue
Aides de vue
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Configuration système requise par le Zend Framework
Version de PHP requise
Extensions PHP
Les composants du Zend Framework
Dépendances internes du Zend Framework
Convention de codage PHP du Zend Framework
Vue d'ensemble
Formatage des fichiers PHP
Conventions de nommage
Style de codage
Informations de copyright