Previous Next

How to Work with Currencies

To use Zend_Currency within your application, create an instance of it without any parameters. This will create an instance of Zend_Currency with your locale set and defines the currency which should be used for this locale.

Example #1 Creating an Instance of Zend_Currency from the Locale

Assume you have 'en_US' set as the set locale by the user or your environment. By passing no parameters while creating the instance you tell Zend_Currency to use the currency from the locale 'en_US'. This leads to an instance with US Dollar set as the currency with formatting rules from 'en_US'.

$currency = new Zend_Currency();

Zend_Currency also supports the usage of an application-wide locale. You can set a Zend_Locale instance in the registry as shown below. With this notation you can avoid setting the locale manually for each instance when you want to use the same locale throughout the application.

// in your bootstrap file
$locale = new Zend_Locale('de_AT');
Zend_Registry::set('Zend_Locale', $locale);

// somewhere in your application
$currency = new Zend_Currency();

Note:

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 see this exception, you should consider setting the locale manually.

Depending on your needs, several parameters can be speicified at instantiation. Each of these parameters is optional and can be omitted. 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. Therefore 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 recognized in any locale an exception will be thrown. Currency short names are always made up of 3 letters, written in uppercase. Well known currency shortnames include USD or EUR.

  • locale:

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

    Note:

    Note that Zend_Currency only accepts locales which include a region. This means that all locales that only include a language will result in an exception. For example the locale en will cause an exception to be thrown whereas the locale en_US will return USD as currency.

Example #2 Other Ways to Create Instances of Zend_Currency

// expect standard locale 'de_AT'

// creates an instance from 'en_US' using 'USD' which is default
// currency for 'en_US'
$currency = new Zend_Currency('en_US');

// creates an instance from the set locale ('de_AT') using 'EUR' as
// currency
$currency = new Zend_Currency();

// creates an instance using 'EUR' as currency, 'en_US' for number
// formating
$currency = new Zend_Currency('en_US', 'EUR');

You can omit any of the parameters to Zend_Currency's constructor if you want to use the default values. This has no negative effect on handling the currencies. It can be useful if, for example, you don't know the default currency for a region.

Note:

For many countries there are several known currencies. Typically, one currency will currently be in use, with one or more ancient currencies. If the 'currency' parameter is suppressed the contemporary currency will be used. The region 'de' for example knows the currencies 'EUR' and 'DEM'... 'EUR' is the contemporary currency and will be used if the currency parameter is omitted.

Creating and Output String from a Currency

To get a numeric value converted to an output string formatted for the currency at hand, use the method toCurrency(). It takes the 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(). It may then be used with toCurrency() to create a currency output string.

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

Example #3 Creating an Output String for a Currency

// creates an instance with 'en_US' using 'USD', which is the default
// values for 'en_US'
$currency = new Zend_Currency('en_US');

// prints '$ 1,000.00'
echo $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 occasionally it is necessary to change this format.

The format of an currency output includes the following parts:

  • Currency symbol, shortname or name:

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

  • Currency position:

    The position of the currency symbol 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 the chapter zend.locale.parsing.html#zend.locale.numbersystems.

  • 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 need to change the format, you should the setFormat() method. It takes an array which should include every option 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 positions can be found in this table.

  • script: Defined which script should be used for displaying digits. The default script for most locales is 'Latn', which includes the digits 0 to 9. Other scripts such as 'Arab' (Arabian) can be used.

  • format: Defines the format which should be used for displaying numbers. This number-format includes for example the thousand separator. You can eighter use a default format by giving a locale identifier, or define the number-format manually. If no format is set the locale from the Zend_Currency object will be used.

  • display: Defines which part of the currency should 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 should be used for the currency representation. The default value is 2.

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

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

  • symbol: Defines the currency symbol which should 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 position of the currency description
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

// creates an instance with 'en_US' using 'USD', 'Latin' and 'en_US' as
// these are the default values from 'en_US'
$currency = new Zend_Currency('en_US');

// prints 'US$ 1,000.00'
echo $currency->toCurrency(1000);

$currency->setFormat(array('display' => Zend_Currency::USE_NAME,
                           'position' => Zend_Currency::RIGHT));

// prints '1.000,00 US Dollar'
echo $currency->toCurrency(1000);

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

$currency->setFormat(array('format' => '##0.00'));
// prints '1000,00 American Dollar'
echo $currency->toCurrency(1000);

Reference Methods for Zend_Currency

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

  • getSymbol():

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

  • getShortName():

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

  • getName():

    Returns the full name of the set 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 set currency or a given one is known to be used. It is possible that a currency is used within several regions, so the return value is always an array.

  • getCurrencyList():

    Returns a list of currencies which are 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 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 set locale is used.

Example #5 Getting Information about Currencies

// creates an instance with 'en_US' using 'USD', 'Latin' and 'en_US'
// as these are the default values from 'en_US'
$currency = new Zend_Currency('en_US');

// prints '$'
echo $currency->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. All default values for the currency will be overwritten when this method is invoked. This includes currency name, abbreviation and symbol.

Example #6 Setting a New Locale

// get the currency for US
$currency = new Zend_Currency('en_US');
print $currency->toCurrency(1000);

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

Zend_Currency Performance Optimization

Zend_Currency's performance can be optimized using Zend_Cache. The static method Zend_Currency::setCache($cache) accepts one option: a Zend_Cache adapter. If the cache adapter is set, the localization data that Zend_Currency uses are cached. There are some static methods for manipulating the cache: getCache(), hasCache(), clearCache() and removeCache().

Example #7 Caching currencies

// creating a cache object
$cache = Zend_Cache::factory('Core',
                             'File',
                             array('lifetime' => 120,
                                   'automatic_serialization' => true),
                             array('cache_dir'
                                       => dirname(__FILE__) . '/_files/'));
Zend_Currency::setCache($cache);
Previous Next
Introduction to Zend Framework
Overview
Installation
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Application
Introduction
Zend_Application Quick Start
Theory of Operation
Examples
Core Functionality
Available Resource Plugins
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Cache
Introduction
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
Zend_Captcha
Introduction
Captcha Operation
CAPTCHA Adapters
Zend_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Migrating from Previous Versions
Zend_Currency
Introduction to Zend_Currency
How to Work with Currencies
Migrating from Previous Versions
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of Dates
Constants for General Date Functions
Working Examples
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
Zend_Db_Table Relationships
Zend_Db_Table_Definition
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dojo build layer support
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_Feed_Reader
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Migrating from previous versions
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Migrating from Previous Versions
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
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Migrating from previous versions
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
Advanced Usage of Zend_Json
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
API overview
Usage Scenarios
Tools
Object oriented access to the LDAP tree using Zend_Ldap_Node
Getting information from the LDAP server
Serializing LDAP data to and from LDIF
Zend_Loader
Loading Files and Classes Dynamically
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrating from previous versions
Zend_Log
Overview
Writers
Formatters
Filters
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Migrating from Previous Versions
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction
Creating and Loading PDF Documents
Save Changes to PDF Documents
Working with Pages
Drawing
Interactive Features
Document Info and Metadata
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Queue
Introduction
Example usage
Framework
Adapters
Customizing Zend_Queue
Stomp
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
Zend_Registry
Using the Registry
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_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Stroage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Amazon_Sqs
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_Twitter
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Test_PHPUnit_Db
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool_Framework
Introduction
Using the CLI Tool
Architecture
Creating Providers to use with Zend_Tool_Framework
Shipped System Providers
Extending and Configuring Zend_Tool_Framework
Zend_Tool_Project
Introduction
Create A Project
Zend Tool Project Providers
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Creating source files
Additional features for translation
Plural notations for Translation
Migrating from previous versions
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Validation Messages
Zend_Version
Getting the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Migrating from Previous Versions
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Zend Framework Requirements
Introduction
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Documentation Standard
Overview
Documentation File Formatting
Recommendations
Recommended Project Structure for Zend Framework MVC Applications
Overview
Recommended Project Directory Structure
Module Structure
Rewrite Configuration Guide
Zend Framework Performance Guide
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information