johndodev / price-formatter
该包最新版本(v2.0)没有提供许可证信息。
在PHP中显示/格式化价格
v2.0
2022-02-25 00:00 UTC
Requires
Requires (Dev)
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-25 05:17:43 UTC
README
在PHP中显示价格。
要求
PHP 5.4+
用法
基本用法
默认设置是为欧洲人设计的,但您可以更改它,请参阅默认选项章节。
use Johndodev\PriceFormatter; // create an instance (see __construct chapter) $priceFormatter = new PriceFormatter(); echo $priceFormatter->format(4); // display "4 €" echo $priceFormatter->format(4, 'USD'); // display 4 $ echo $priceFormatter->format(4, '$'); // display 4 $ echo $priceFormatter->format(4, 'USD')->symbolBefore()->symbolSep(''); // display $4
方法
所有方法都是可链式调用的
echo $priceFormatter->format($numberToFormat, $currency = null) // remove trailing zeros if necessary: 5.00 output 5 but 5.50 output 5.50) ->autoTrailingZeros(true) // set the symbol separator ->symbolSep(' ') // set the decimals separator ->decSep('.') // set the maximum number of decimals to show ->decimals(2) // put the symbol after the value ->symbolAfter() // or before ->symbolBefore() // but you can define the position with a variable ->symbolPosition(PriceFormatter::SYMBOL_POSITION_AFTER) // set the thousands separator ->thousandsSep(',') // remove trailing zeros (decimals), e.g.: 5.00 will output 5, 5.50 will output 5.5 ->trimTrailingZeros(true) // unbreakable spaces: replace " " by " " ->unbreakable(true);
__construct
您可以创建任意多个实例(即服务),每个实例都有自己的默认选项(下一章是默认选项)
PriceFormatter::__construct($options = []) $euroFormatter = new PriceFormatter(['currency' => 'EUR']); $euroFormatter = new PriceFormatter(['currency' => '€']); $usdFormatter = new PriceFormatter([ 'currency' => 'USD', 'symbolPosition' => PriceFormatter::SYMBOL_POSITION_BEFORE, ]);
默认选项
您可以针对每个实例设置所有这些设置,以下为默认值
$priceFormatter = new PriceFormatter([ 'currency' => 'EUR', 'decimals' => 2, 'decSep' => '.', 'thousandsSep' => '', 'symbolPosition' => PriceFormatter::SYMBOL_POSITION_AFTER, 'symbolSep' => ' ', 'unbreakable' => true, 'trimTrailingZeros' => false, 'autoTrailingZeros' => true, ]);
示例
// no spaces between currency and value $priceFormatter = new PriceFormatter(['symbolSep' => '']); // display 5€ echo $priceFormatter->format(5); // but all options can be overriden for one format() echo $priceFormatter->format(5)->symbolSep(' '); // display 5 € echo $priceFormatter->format(5); // then display 5€ again
货币和符号
您可以使用以下代码 AUD
$, CAD
$, CHF
CHF, CNY
¥, EUR
€, GBP
£, HKD
$, JPY
¥, NOK
kr, SEK
kr, USD
$.
如果您想要格式化不受支持的货币,请使用符号(http://www.xe.com/symbols.php)
// 5 ฿ echo $priceFormatter->format(5, '฿');
运行测试
> composer install
> php vendor/bin/phpunit --testsuite PriceFormatter