PHP code example of johndodev / price-formatter

1. Go to this page and download the library: Download johndodev/price-formatter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

johndodev / price-formatter example snippets


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 "&nbsp;"
->unbreakable(true);

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

// 5 ฿
echo $priceFormatter->format(5, '฿'); 

> composer install
> php vendor/bin/phpunit --testsuite PriceFormatter