Previous Next

Normalization and Localization

Zend_Locale_Format is a internal component used by Zend_Locale. All locale aware classes use Zend_Locale_Format for normalization and localization of numbers and dates. Normalization involves parsing input from a variety of data representations, like dates, into a standardized, structured representation, such as a PHP array with year, month, and day elements.

The exact same string containing a number or a date might mean different things to people with different customs and conventions. Disambiguation of numbers and dates requires rules about how to interpret these strings and normalize the values into a standardized data structure. Thus, all methods in Zend_Locale_Format require a locale in order to parse the input data.

Note: Default "root" Locale

If no locale is specified, then normalization and localization will use the standard "root" locale, which might yield unexpected behavior, if the input originated in a different locale, or output for a specific locale was expected.

Number normalization: getNumber($input, Array $options)

There are many » number systems different from the common » decimal system (e.g. "3.14"). Numbers can be normalized with the getNumber() function to obtain the standard decimal representation. For all number-related discussions in this manual, » Arabic/European numerals (0,1,2,3,4,5,6,7,8,9) are implied, unless explicitly stated otherwise. The options array may contain a 'locale' to define grouping and decimal characters. The array may also have a 'precision' to truncate excess digits from the result.

Example #1 Number normalization

$locale = new Zend_Locale('de_AT');
$number = Zend_Locale_Format::getNumber('13.524,678',
                                        array('locale' => $locale,
                                              'precision' => 3)
                                       );

print $number; // will return 13524.678

Precision and Calculations

Since getNumber($value, array $options = array()) can normalize extremely large numbers, check the result carefully before using finite precision calculations, such as ordinary PHP math operations. For example, if ((string)int_val($number) != $number) { use » BCMath or » GMP . Most PHP installations support the BCMath extension.

Also, the precision of the resulting decimal representation can be rounded to a desired length with getNumber() with the option 'precision'. If no precision is given, no rounding occurs. Use only PHP integers to specify the precision.

If the resulting decimal representation should be truncated to a desired length instead of rounded the option 'number_format' can be used instead. Define the length of the decimal representation with the desired length of zeros. The result will then not be rounded. So if the defined precision within number_format is zero the value "1.6" will return "1", not "2. See the example nearby:

Example #2 Number normalization with precision

$locale = new Zend_Locale('de_AT');
$number = Zend_Locale_Format::getNumber('13.524,678',
                                        array('precision' => 1,
                                              'locale' => $locale)
                                       );
print $number; // will return 13524.7

$number = Zend_Locale_Format::getNumber('13.524,678',
                                        array('number_format' => '#.00',
                                              'locale' => $locale)
                                       );
print $number; // will return 13524.67

Number localization

toNumber($value, array $options = array()) can localize numbers to the following supported locales . This function will return a localized string of the given number in a conventional format for a specific locale. The 'number_format' option explicitly specifies a non-default number format for use with toNumber().

Example #3 Number localization

$locale = new Zend_Locale('de_AT');
$number = Zend_Locale_Format::toNumber(13547.36,
                                       array('locale' => $locale));

// will return 13.547,36
print $number;

Note: Unlimited length

toNumber() can localize numbers with unlimited length. It is not related to integer or float limitations.

The same way as within getNumber(), toNumber() handles precision. If no precision is given, the complete localized number will be returned.

Example #4 Number localization with precision

$locale = new Zend_Locale('de_AT');
$number = Zend_Locale_Format::toNumber(13547.3678,
                                       array('precision' => 2,
                                             'locale' => $locale));

// will return 13.547,37
print $number;

Using the option 'number_format' a self defined format for generating a number can be defined. The format itself has to be given in CLDR format as described below. The locale is used to get separation, precision and other number formatting signs from it. German for example defines ',' as precision separation and in English the '.' sign is used.

Format tokens for self generated number formats
Token Description Example format Generated output
#0 Generates a number without precision and separation #0 1234567
, Generates a separation with the length from separation to next separation or to 0 #,##0 1,234,567
#,##,##0 Generates a standard separation of 3 and all following separations with 2 #,##,##0 12,34,567
. Generates a precision #0.# 1234567.1234
0 Generates a precision with a defined length #0.00 1234567.12

Example #5 Using a self defined number format

$locale = new Zend_Locale('de_AT');
$number = Zend_Locale_Format::toNumber(13547.3678,
                                       array('number_format' => '#,#0.00',
                                             'locale' => 'de')
                                      );

// will return 1.35.47,36
print $number;

$number = Zend_Locale_Format::toNumber(13547.3,
                                       array('number_format' => '#,##0.00',
                                             'locale' => 'de')
                                       );

// will return 13.547,30
print $number;

Number testing

isNumber($value, array $options = array()) checks if a given string is a number and returns true or false.

Example #6 Number testing

$locale = new Zend_Locale();
if (Zend_Locale_Format::isNumber('13.445,36', array('locale' => 'de_AT')) {
    print "Number";
} else {
    print "not a Number";
}

Float value normalization

Floating point values can be parsed with the getFloat($value, array $options = array()) function. A floating point value will be returned.

Example #7 Floating point value normalization

$locale = new Zend_Locale('de_AT');
$number = Zend_Locale_Format::getFloat('13.524,678',
                                       array('precision' => 2,
                                             'locale' => $locale)
                                      );

// will return 13524.68
print $number;

Floating point value localization

toFloat() can localize floating point values. This function will return a localized string of the given number.

Example #8 Floating point value localization

$locale = new Zend_Locale('de_AT');
$number = Zend_Locale_Format::toFloat(13547.3655,
                                      array('precision' => 1,
                                            'locale' => $locale)
                                     );

// will return 13.547,4
print $number;

Floating point value testing

isFloat($value, array $options = array()) checks if a given string is a floating point value and returns true or false.

Example #9 Floating point value testing

$locale = new Zend_Locale('de_AT');
if (Zend_Locale_Format::isFloat('13.445,36', array('locale' => $locale)) {
    print "float";
} else {
    print "not a float";
}

Integer value normalization

Integer values can be parsed with the getInteger() function. A integer value will be returned.

Example #10 Integer value normalization

$locale = new Zend_Locale('de_AT');
$number = Zend_Locale_Format::getInteger('13.524,678',
                                         array('locale' => $locale));

// will return 13524
print $number;

Integer point value localization

toInteger($value, array $options = array()) can localize integer values. This function will return a localized string of the given number.

Example #11 Integer value localization

$locale = new Zend_Locale('de_AT');
$number = Zend_Locale_Format::toInteger(13547.3655,
                                        array('locale' => $locale));

// will return 13.547
print $number;

Integer value testing

isInteger($value, array $options = array()) checks if a given string is a integer value and returns true or false.

Example #12 Integer value testing

$locale = new Zend_Locale('de_AT');
if (Zend_Locale_Format::isInteger('13.445', array('locale' => $locale)) {
    print "integer";
} else {
    print "not a integer";
}

Numeral System Conversion

Zend_Locale_Format::convertNumerals() converts digits between different » numeral systems , including the standard Arabic/European/Latin numeral system (0,1,2,3,4,5,6,7,8,9), not to be confused with » Eastern Arabic numerals sometimes used with the Arabic language to express numerals. Attempts to use an unsupported numeral system will result in an exception, to avoid accidentally performing an incorrect conversion due to a spelling error. All characters in the input, which are not numerals for the selected numeral system, are copied to the output with no conversion provided for unit separator characters. Zend_Locale* components rely on the data provided by CLDR (see their »  list of scripts grouped by language).

In CLDR and hereafter, the Europena/Latin numerals will be referred to as "Latin" or by the assigned 4-letter code "Latn". Also, the CLDR refers to this numeral systems as "scripts".

Suppose a web form collected a numeric input expressed using Eastern Arabic digits "١‎٠٠". Most software and PHP functions expect input using Arabic numerals. Fortunately, converting this input to it's equivalent Latin numerals "100" requires little effort using convertNumerals($inputNumeralString, $sourceNumeralSystem, $destNumeralSystem) , which returns the $input with numerals in the script $sourceNumeralSystem converted to the script $destNumeralSystem.

Example #13 Converting numerals from Eastern Arabic scripts to European/Latin scripts

$arabicScript = "١‎٠٠";   // Arabic for "100" (one hundred)
$latinScript = Zend_Locale_Format::convertNumerals($arabicScript,
                                                   'Arab',
                                                   'Latn');

print "\nOriginal:   " . $arabicScript;
print "\nNormalized: " . $latinScript;

Similarly, any of the supported numeral systems may be converted to any other supported numeral system.

Example #14 Converting numerals from Latin script to Eastern Arabic script

$latinScript = '123';
$arabicScript = Zend_Locale_Format::convertNumerals($latinScript,
                                                    'Latn',
                                                    'Arab');

print "\nOriginal:  " . $latinScript;
print "\nLocalized: " . $arabicScript;

Example #15 Getting 4 letter CLDR script code using a native-language name of the script

function getScriptCode($scriptName, $locale)
{
    $scripts2names = Zend_Locale_Data::getList($locale, 'script');
    $names2scripts = array_flip($scripts2names);
    return $names2scripts[$scriptName];
}
echo getScriptCode('Latin', 'en'); // outputs "Latn"
echo getScriptCode('Tamil', 'en'); // outputs "Taml"
echo getScriptCode('tamoul', 'fr'); // outputs "Taml"

List of supported numeral systems

List of supported numeral systems
Notation Name Script
Arabic Arab
Balinese Bali
Bengali Beng
Devanagari Deva
Gujarati Gujr
Gurmukhi Guru
Kannada Knda
Khmer Khmr
Lao Laoo
Limbu Limb
Malayalam Mlym
Mongolian Mong
Myanmar Mymr
New_Tai_Lue Talu
Nko Nkoo
Oriya Orya
Tamil Taml
Telugu Telu
Thai Tale
Tibetan Tibt

Previous Next
Introduction to Zend Framework
Présentation
Installation
Zend_Acl
Introduction
Affiner les Contrôles d'Accès
Utilisation avancée
Zend_Amf
Introduction
Zend_Amf_Server
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
Aspect théorique
Les frontends Zend_Cache
Les backends Zend_Cache
Zend_Captcha
Introduction
Opération Captcha
Adaptateurs Captcha
Zend_Config
Introduction
Aspect théorique
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
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
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
Aspect 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
Validateurs pour Zend_File_Transfer
Filtres pour Zend_File_Transfer
Migrer à partir des versions précédentes
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 to Gdata
Authentification par procédé AuthSub
Using the Book Search Data API
Authentification avec ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Utilisation des albums Web Picasa
Using the YouTube Data API
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 locales
Migrer à partir des versions précédentes
Zend_Log
Présentation
Rédacteurs (Writers)
Formateurs (mise en forme)
Filtres
Zend_Mail
Introduction
Envoyer des émail en utilisant SMTP
Envoyer plusieurs émail par connexion SMTP
Utiliser différents transports
Émail 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 émail
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
Utilisation
Configuration
Utilisation avancée
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_ProgressBar
Zend_ProgressBar
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
Jeu de caractères
Extensibility
Agir avec Lucene Java
Avancé
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_Twitter
Zend_Service_Yahoo
Zend_Session
Introduction
Usage basique
Utilisation avancée
Gestion générale de la session
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL
Auto découverte
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Utiliser Zend_TimeSync
Zend_Translate
Introduction
Adaptateurs pour Zend_Translate
Utiliser les adaptateurs de traduction
Migrer à partir des versions précédentes
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Classes de validation standard
Chaînes de validation
Écrire 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
Zend Framework Performance Guide
Introduction
Class Loading
Internationalisation (i18n) and Localisation (l10n)
View Rendering
Informations de copyright