aleostudio/currency-formatter

一个简单的PHP包,用于格式化EUR-USD和其他货币,以及货币与浮点数的转换

dev-master 2019-07-19 10:30 UTC

This package is auto-updated.

Last update: 2024-09-12 20:36:25 UTC


README

一个简单的单例实例,具有流畅的方法,用于以正确的货币语法格式化浮点价格,可选地添加前缀或后缀,并指定小数位数。

将整数/浮点值转换为格式化的货币

CurrencyFormatter::set('EUR')->value(1000.46);
  • 将返回格式化的字符串:€ 1.000,46
CurrencyFormatter::set('EUR')->value(1000.46)->withPrefix('EURO')->decimals(3);
  • 将返回格式化的字符串:EURO 1.000,460
CurrencyFormatter::set('EUR')->value(1000.46)->withSuffix('Eur');
  • 将返回格式化的字符串:1.000,46 Eur
CurrencyFormatter::set('USD')->value(1000.46)->withPrefix('$');
  • 将返回格式化的字符串:$ 1,000.46
CurrencyFormatter::set('USD')->value(1000.46)->withPrefix('USD')->decimals(3);
  • 将返回格式化的字符串:USD 1,000.460
CurrencyFormatter::set('USD')->value(1000.46)->withSuffix('USD');
  • 将返回格式化的字符串:1,000.46 USD

将货币字符串转换为有效的浮点值

CurrencyFormatter::toFloat('EUR 1.000,45');
  • 将返回浮点值:1000.45
CurrencyFormatter::toFloat('1,000.45 USD');
  • 将返回浮点值:1000.45

安装

使用以下命令克隆包

git clone git@github.com:aleostudio/currency-formatter.git

使用以下命令安装其依赖项

composer install

然后创建一个新的PHP文件,尝试以下代码

require_once __DIR__ . '/vendor/autoload.php';

use AleoStudio\CurrencyFormatter\CurrencyFormatter;

echo CurrencyFormatter::set('EUR')->value(1000.46) . '<br />';
echo CurrencyFormatter::set('EUR')->value(1000.46)->withPrefix('EURO')->decimals(3) . '<br />';
echo CurrencyFormatter::set('EUR')->value(1000.46)->withSuffix('Eur') . '<br />';

echo CurrencyFormatter::set('USD')->value(1000.46)->withPrefix('$') . '<br />';
echo CurrencyFormatter::set('USD')->value(1000.46)->withPrefix('USD')->decimals(3) . '<br />';
echo CurrencyFormatter::set('USD')->value(1000.46)->withSuffix('USD') . '<br />';

echo CurrencyFormatter::toFloat('EUR 1.000,45') . '<br />';
echo CurrencyFormatter::toFloat('1,000.45 USD') . '<br />';

单元测试

安装PHPUnit,然后使用以下命令运行测试

phpunit --bootstrap vendor/autoload.php tests/CurrencyFormatterTest.php 

README是用以下工具生成的:https://stackedit.io/app