lukaszwit / currency
使用浮点运算安全处理货币
0.3.0
2014-11-16 15:20 UTC
Requires
- php: ~5.4
Requires (Dev)
- phpunit/phpunit: ~4.3
- satooshi/php-coveralls: dev-master
This package is not auto-updated.
Last update: 2024-09-24 02:59:33 UTC
README
货币包引入了严格类型和精度安全的容器来处理货币。货币在内部以字符串形式保存金额(PHP中浮点数的唯一安全表示)。它确保一旦在特定货币中定义了任何金额,就无法更改其类型,并且您可以给方法添加类型提示以使用任何货币或确切的一种货币。内部此库使用SplType扩展和SplString类。将金额保持在字符串中可以防止浮点问题,并允许您使用bcMath等高精度库来处理算术运算。
查看PHP中浮点数的工作原理 - https://php.ac.cn/manual/en/language.types.float.php
查看当您依赖于浮点精度时会发生什么 - http://stackoverflow.com/questions/3726721/php-math-precision
此包还支持维基百科中列出的知名加密货币 - http://en.wikipedia.org/wiki/Cryptocurrency#List_of_cryptocurrencies
安装
首先需要安装SPL_Types - PECL扩展
$ pecl install SPL_Types
如果已安装SPL_Types,现在可以通过Composer安装currency包
$ composer require lukaszwit/currency
用法
<?php use Currency\Eur; $eur = new Eur; $eur = '10'; // this is OK $eur = 10; // but this emits UnexpectedValueException
类型提示
<?php use Currency\Usd; use Currency\AbstractCurrency as Currency; class Example { public function workWithCurrency(Currency $c) { } public function workOnlyWithUsd(Usd $usd) { } }
在examples目录中查看更多示例 - https://github.com/lukaszwit/currency/tree/master/examples.
测试
$ phpunit
贡献
请参阅CONTRIBUTING以获取详细信息。
鸣谢
许可
MIT许可(MIT)。有关更多信息,请参阅许可文件。