【问题标题】:Zend_Currency value with cents instead of dollarsZend_Currency 值用美分而不是美元
【发布时间】:2010-12-02 09:02:44
【问题描述】:
我正在使用 Zend_Currency 并希望将值存储为美分(与美元相反),因为系统的其他部分以美分工作。所以,我想以美分初始化和检索 Zend_Currency 对象的值,有没有办法以这种方式配置 Zend_Currency?
我知道我可以在检索值时除以 100,但我不知道当/如果我们需要国际化时这将是多么兼容。 IE。 所有货币都是 100“美分”单位对“美元”吗?
【问题讨论】:
标签:
php
zend-framework
zend-currency
【解决方案1】:
所有货币都是 100“美分”单位对“美元”吗?
没有。
虽然大多数都有,但也有一些以“5”为底或以“1000”为底或根本没有小数。
来源:http://en.wikipedia.org/wiki/List_of_circulating_currencies
您应该使用 Zend Currency 来存储原始值并让它为您进行转换。
// 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());
注意:My_Currency_Exchange() 是我创建的一个虚拟类,它看起来像这样:
<?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';
}
}
}
输出:
float(100.5) float(261.0387)