PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

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 565. Number normalization

<?php
$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 566. Number normalization with precision

<?php
$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

Zend Framework