commerceguys / pricing
dev-master
2017-05-10 14:14 UTC
Requires
- commerceguys/intl: ~0.5
This package is auto-updated.
Last update: 2022-02-01 12:36:44 UTC
README
已废弃:请使用moneyphp/money代替。
一个用于处理价格的PHP 5.4+库。
依赖于commerceguys/intl来获取货币信息和格式化。
价格
价格是一个值对象。每个操作(加、减、乘、除、舍入)都会产生一个新的价格实例。所有金额都作为字符串传递,并使用bcmath进行操作。
use CommerceGuys\Intl\Currency\CurrencyRepository; use CommerceGuys\Pricing\Price; $currencyRepository = new CurrencyRepository; $currency = $currencyRepository->get('EUR'); // $firstPrice, $secondPrice, $thirdPrice, $total are all Price instances. $firstPrice = new Price('99.99', $currency); $secondPrice = new Price('100', $currency); $thirdPrice = new Price('20.307', $currency); // Every operation produces a new Price instance. $total = $firstPrice ->add($secondPrice) ->subtract($thirdPrice) ->multiply('4') ->divide('2'); echo $total; // 359.366 EUR echo $total->round(); // 359.37 EUR echo $total->round(Price::ROUND_HALF_UP, 1); // 359.4 EUR echo $total->greaterThan($firstPrice); // true
货币转换
use CommerceGuys\Intl\Currency\CurrencyRepository; use CommerceGuys\Pricing\Price; $currencyRepository = new CurrencyRepository; $eur = $currencyRepository->get('EUR'); $usd = $currencyRepository->get('USD'); // Use an external library to get an actual exchange rate. $rate = 1; $eurPrice = new Price('100', $eur); $usdPrice = $eurPrice->convert($usd, $rate); echo $usdPrice;
可以使用类似Swap的外部库来获取汇率。
格式化
使用commerceguys/intl提供的NumberFormatter类。
use CommerceGuys\Intl\Currency\CurrencyRepository; use CommerceGuys\Intl\NumberFormat\NumberFormatRepository; use CommerceGuys\Intl\Formatter\NumberFormatter; use CommerceGuys\Pricing\Price; $currencyRepository = new CurrencyRepository; $currency = $currencyRepository->get('USD'); $price = new Price('99.99', $currency); $numberFormatRepository = new NumberFormatRepository; $numberFormat = $numberFormatRepository->get('en-US'); $currencyFormatter = new NumberFormatter($numberFormat, NumberFormatter::CURRENCY); echo $currencyFormatter->formatCurrency($price->getAmount(), $price->getCurrency()); // $99.99