amoreno/currency-formatter

根据货币代码格式化货币的PHP库

0.4.0 2017-02-08 19:15 UTC

This package is auto-updated.

Last update: 2024-09-16 02:26:47 UTC


README

货币格式化的PHP库。

为什么创建这个?

我找到的大多数货币格式化器都依赖于区域设置。我当前对格式化器的需求需要将区域知识解耦。

安装

composer require axm/currency-formatter

使用

格式化器由货币集合提供动力,该集合包含一组格式化规则。您可以创建自己的集合,然后将它设置为格式化器

$settings = [
	'currency_symbol' => '$',
	'decimal_spaces' => 2,
	'decimal_separator' => '.',
	'thousand_separator' => ','
];

$config = new Config('USD', $settings);

$collection = new Collection();
$collection->push($config);

Formatter::setCollection($collection);
echo Formatter::format('1234.56', 'USD'); // $1,234.56 USD

上述内容将配置、集合和格式化器类分离,以实现最大灵活性。它允许您定义自己的规则集,并仅加载实际需要的规则,以获得微小的性能提升。

然而,上述内容似乎需要一些配置。这就是Loader类发挥作用的地方

/*
Given a JSON string of currency settings:
[
  {
    "iso_code": "USD",
    "currency_symbol": "$",
    "decimal_spaces": 2,
    "decimal_separator": ".",
    "thousand_separator": ",",
	 "label": "Dollars"
  },
  {
    "iso_code": "GBP",
    "currency_symbol": "£",
    "decimal_spaces": 2,
    "decimal_separator": ",",
    "thousand_separator": ".",
	 "label": null // if omitted will use the iso_code
  },
  {
    "iso_code": "CLP",
    "currency_symbol": "$",
    "decimal_spaces": 0,
    "decimal_separator": ",",
    "thousand_separator": "."
  }
]
*/

$settings = json_decode(file_get_contents(json_file));
Loader::fromArray(settings);

// Your Format class now has a collection with 3 currency rules
echo Format::(1234.56, 'USD'); // $1,234.56 Dollars
echo Format::(1234.56, 'GBP'); // £1.234,56 GBP
echo Format::(1234.56, 'CLP'); // $1.235 CLP

只要您有一个符合预期格式的数组,使用Loader是最好的方法。

自定义输出

如果您希望有更细粒度的控制,您可以创建自己的规则集,或像这样覆盖现有的规则

//creating a custom rule
Formatter::getCollection()->push([
	'iso_code' => 'USD2',
	'currency_symbol' => '',
	'decimal_spaces' => 2,
	'decimal_separator' => '.',
	'thousand_separator' => ',',
	'label' => ' big ones'
]);
Formatter::format(1234.56, 'USD2'); // 1,234.56 big ones

//overriding an existing rule
echo Format::(1234.56, 'USD2', [
	'currency_symbol' => '$$ ',
	'decimal_spaces' => 4,
	'label' => 'bucks'
]); // $$ 1,234.5600 big ones

测试

该库使用Kahlan进行测试。要运行测试,请确保已安装require-dev模块

composer install
./bin/kahlan

许可

MIT许可证

版权(c)2016 以下是对任何获得本软件及其相关文档文件(以下简称“软件”)副本的任何个人免费许可,允许在不限制的情况下处理软件,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售软件副本,并允许向提供软件的个人提供使用软件的权利,前提是遵守以下条件

上述版权声明和本许可声明应包含在软件的副本或实质性部分中。

软件按“原样”提供,不提供任何明示或暗示的保证,包括但不限于适销性、针对特定目的的适用性和非侵权性。在任何情况下,作者或版权所有者均不对任何索赔、损害或其他责任承担责任,无论该责任是基于合同、侵权或其他方式产生,无论是从软件或软件的使用或任何其他方式产生。