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

Using precision on currencies

When working with currencies they you probably also have to handle precision. Most currencies use a precision of 2. This means that when you have 100 US dollars you could also have 50 cents. The related value is simply a floating value.

<?php
$currency 
= new Zend_Currency(
    array(
        
'value'    => 1000.50,
        
'currency' => 'USD',
    )
);

print 
$currency// Could return '$ 1.000,50'

Of course, as the default precision is 2, you will get '00' for the decimal value when there is no precision to display.

<?php
$currency 
= new Zend_Currency(
    array(
        
'value'    => 1000,
        
'currency' => 'USD',
    )
);

print 
$currency// Could return '$ 1.000,00'

To get rid of this default precision you could simply use the precision option and set it to '0'. And you can set any other precision you want to use between 0 and 9. All values will be rounded or streched when they don't fit the set precision.

<?php
$currency 
= new Zend_Currency(
    array(
        
'value'     => 1000,30,
        
'currency'  => 'USD',
        
'precision' => 0
    
)
);

print 
$currency// Could return '$ 1.000'

Zend Framework