nethask/currency

货币转换和格式化

1.0.0 2017-07-01 22:52 UTC

This package is not auto-updated.

Last update: 2024-09-20 19:35:14 UTC


README

https://github.com/moltin/currency 分支而来

Moltin 货币作曲家包使得在您的应用程序中实现多货币定价变得简单,并使用众多提供的数据存储之一存储汇率数据。如果您希望数据存储在其他地方,还可以注入自己的数据存储。

安装

http://www.getcomposer.org/download 下载并安装 composer

将以下内容添加到您的项目 composer.json 文件中

{
    "require": {
        "moltin/currency": "1.0.*@dev"
    }
}

完成后,只需运行 php composer.phar install,即可使用该包。

使用方法

以下是该包的基本使用指南。

实例化货币

在开始之前,您需要知道将要使用哪种存储、货币和汇率方法。汇率方法定义了您的汇率是从哪里检索的。货币方法用于检索当前应用程序支持的所有货币。

在此示例中,我们将使用货币文件、汇率文件和会话进行存储。

use Moltin\Currency\Currency as Currency;
use Moltin\Currency\Format\Runtime as RuntimeFormat;
use Moltin\Currency\Exchange\OpenExchangeRates as OpenExchange;

$currency = new Currency(new OpenExchange($app_id), new RuntimeFormat);

设置值

现在,您已经实例化了货币,需要告诉它您想要转换的值。您可以使用以下方法来完成。

$currency->convert(9.33)->from('GBP');

获取值

您可以执行的最基本操作是从方法中检索原始值。

// Returns 9.33
$value = $currency->value();

货币格式化

默认情况下,货币设置为 GBP,因此调用货币将格式化值为带有 £ 和正确的十进制和千位分隔符的字符串。

// Returns £9.33
$value = $currency->format();

四舍五入到常用值

内置了许多常用定价格式,使“漂亮”的价格易于实现。这些格式更改默认值并返回对象,以允许链式操作。

// Sets value to 10.00
$currency->zeros();

// Sets value to 9.99
$currency->nines();

// Sets value to 9.50
$currency->fifty();

// Returns £9.50
$value = $currency->fifty()->format();

货币汇率

该包使得在货币之间快速切换变得尽可能简单。在每次交换之前,值重置为默认值,以确保分配正确的价格。

// Returns ~$14.47
$value = $currency->convert(9.33)->from('GBP')->to('USD')->format();

// Returns ~14.50
$value = $currency->convert(9.33)->from('GBP')->to('USD')->fifty()->value();

重置值

在使用交换或任何四舍五入函数检索默认值之后,必须调用重置。

// Returns 10.00
$value = $currency->zeros()->value();

// Returns 9.33
$value = $currency->reset()->value();