Zend_Currency value with cents instead of dollars

422 Views Asked by At

I am using Zend_Currency and would like to store the values in cents as (opposed to to dollars) due to other parts of the system that work in cents. So, I would like to initialise and retrieve values for Zend_Currency objects in cents, is there a way to configure Zend_Currency this way?

I am aware I could just divide by 100 when I retrieve the value, but I don't know how compatible this would be when/if we need to internationalize. ie. Are all currencies 100 "cent" units to the "dollar".

1

There are 1 best solutions below

0
On

Are all currencies 100 "cent" units to the "dollar"?

No.

Although most do, there are a few that have a base of '5' or a base of '1000' or no decimal at all.

source: http://en.wikipedia.org/wiki/List_of_circulating_currencies

You should be using Zend Currency to store the raw value and let it do conversions for you.

    // original money
    $money = new Zend_Currency('US');
    $money->setValue('100.50');

    // conversion
    $oman = new Zend_Currency('OM');
    $oman->setService(new My_Currency_Exchange());
    $oman->setValue($money->getValue(), $money->getShortName());
    var_dump($money->getValue(), $oman->getValue());

Note: My_Currency_Exchange() is a dummy class I've created, it looks like this:

<?php

class My_Currency_Exchange implements Zend_Currency_CurrencyInterface
{
public function getRate($from, $to)
{
    if ($from !== "USD") {
        throw new Exception ('We only do USD : '  . $from);
    }

    switch ($to) {
        case 'OMR':
            // value from xe.com as of today
            return '2.59740';
    }
    }
}

output: float(100.5) float(261.0387)