thedevick / precise-money
使用PHP精确操作货币。
2.1.0
2023-08-15 22:03 UTC
Requires
- ext-bcmath: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.21
- phpunit/phpunit: ^10.2
- symfony/var-dumper: ^6.2
- vimeo/psalm: ^5.13
README
货币对象
The Money 类是一个 不可变 类,它表示货币金额。您可以使用数值字符串或其它 Money 对象添加、减去、乘以和除以对象中的金额。此外,Money 类还支持 JSON 序列化和 Stringable。
<?php use TheDevick\PreciseMoney\Calculator\BCMathCalculator; use TheDevick\PreciseMoney\Money; $money = new Money('10', new BCMathCalculator(3)); // Start with $10.000, using the BCMathCalculator with scale 3 (The default is using scale 10) $money = $money->addMoney(new Money('3')); // Add $3.000 $money = $money->add('5.235'); // Add $5.235 return json_encode($money); // Returns {"amount":"18.235"}
内部
内部,Money 对象使用数值字符串存储金额。
为什么使用精确货币?
此包提供了一种精确计算货币的方法。在其它库中,金额以整数的分存储,您无法计算例如每千瓦时价格,因为每千瓦时价格通常有超过4位小数。但自从 Precise Money 包以数值字符串的形式存储金额,您可以存储您想要的任意位数的小数。
计算
今天,我们仅提供 BCMathCalculator
,它实现了 CalculatorInterface
。
测试
计算器
要测试实现了 Calculator 接口 的计算器类,您可以使用计算器测试特质。它包含一些可以帮助您编写测试的方法
generateCalculatorMessage(CalculatorInterface $calculator)
返回一个关于计算器类和比例的友好信息。在断言中使用$message
参数时很有用。assertCalculatorAddMethod($calculator, $expected, $x, $y)
此方法断言计算器加法方法。assertCalculatorAddMethodComplete($calculator)
此方法断言使用计算器的多种操作。