Documentation

How much is my currency? - Zend_Currency

How much is my currency?

When you are working with currencies then you normally want to display an amount of money. And when you work with different currencies then you have to do this with three different things. The amount you want to display, the precision you want to use, and probably the exchange rate.

Working with currency values

The currency value, a.k.a. the money, you want to use can easily be set by using the value option.

  1. $currency = new Zend_Currency(
  2.     array(
  3.         'value'    => 1000,
  4.         'currency' => 'USD',
  5.     )
  6. );
  7.  
  8. print $currency; // Could return '$ 1.000'

Using the setFormat() method with this array option, and also by using the setValue() method you can set the value afterwards.

  1. $currency = new Zend_Currency(
  2.     array(
  3.         'value'    => 1000,
  4.         'currency' => 'USD',
  5.     )
  6. );
  7.  
  8. print $currency->setValue(2000); // Could return '$ 2.000'

With the getValue() method you will get the actual set value.

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.

  1. $currency = new Zend_Currency(
  2.     array(
  3.         'value'    => 1000.50,
  4.         'currency' => 'USD',
  5.     )
  6. );
  7.  
  8. 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.

  1. $currency = new Zend_Currency(
  2.     array(
  3.         'value'    => 1000,
  4.         'currency' => 'USD',
  5.     )
  6. );
  7.  
  8. 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.

  1. $currency = new Zend_Currency(
  2.     array(
  3.         'value'     => 1000,30,
  4.         'currency'  => 'USD',
  5.         'precision' => 0
  6.     )
  7. );
  8.  
  9. print $currency; // Could return '$ 1.000'

Copyright

© 2006-2021 by Zend by Perforce. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.

Contacts