PHP code example of byrokrat / amount

1. Go to this page and download the library: Download byrokrat/amount 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/ */

    

byrokrat / amount example snippets


use byrokrat\amount\Amount;

$amount = new Amount('100.6');

// outputs 1 (true)
echo $amount->isGreaterThan(new Amount('50'));

// round to 0 decimal digits
$roundedAmount = $amount->roundTo(0);

// outputs 101.00
echo $roundedAmount;

use byrokrat\amount\Amount;

$formattedAmount = "2 000:50";

$amount = Amount::createFromFormat($formattedAmount, ":", " ");

echo $amount;  // outputs 2000.50

use byrokrat\amount\Currency\SEK;
use byrokrat\amount\Currency\EUR;

$sek = new SEK('100');

// throws an exception
$sek->add(new EUR('1'));

use byrokrat\amount\Currency\SEK;

$sek = new SEK('100');

// works as intended, outputs 101.00
echo $sek->add(new SEK('1'));

use byrokrat\amount\Currency\SEK;
use byrokrat\amount\Currency\EUR;

// One euro is exchanged into swedish kronas using the exchange rate 9.27198929
// resulting in the value of SEK 9.27198929
echo $sek = SEK::createFromExchange(new EUR('1'), '9.27198929');

use byrokrat\amount\Currency\EUR;

// Create some amount of euros
$money = new EUR('1234567.89');

// Create a currency formatter with swedish formatting rules
$formatter = new NumberFormatter('sv_SE', NumberFormatter::CURRENCY);

// Format euros according to swedish standards, outputs 1 234 567:89 €
echo $formatter->formatCurrency($money->getFloat(), $money->getCurrencyCode());

namespace byrokrat\amount;
$amount = new Amount('1.5');

// outputs 2
echo $amount->roundTo(0, new Rounder\RoundUp);

// outputs 1
echo $amount->roundTo(0, new Rounder\RoundDown);

// outputs 1
echo $amount->roundTo(0, new Rounder\RoundTowardsZero);

// outputs 2
echo $amount->roundTo(0, new Rounder\RoundAwayFromZero);

// outputs 2
echo $amount->roundTo(0, new Rounder\RoundHalfUp);

// outputs 1
echo $amount->roundTo(0, new Rounder\RoundHalfDown);

// outputs 1
echo $amount->roundTo(0, new Rounder\RoundHalfTowardsZero);

// outputs 2
echo $amount->roundTo(0, new Rounder\RoundHalfAwayFromZero);

// outputs 2
echo $amount->roundTo(0, new Rounder\RoundHalfToEven);

// outputs 1
echo $amount->roundTo(0, new Rounder\RoundHalfToOdd);

use byrokrat\amount\Amount;
$money = new Amount('100');

list($receiverA, $receiverB) = $money->allocate([30, 70]);

// outputs 30
echo $receiverA;

// outputs 70
echo $receiverB;

use byrokrat\amount\Amount;

$money = new Amount('0.05');

list($receiverA, $receiverB) = $money->allocate([30, 70]);

// outputs 0.03
echo $receiverA;

// outputs 0.02
echo $receiverB;

list($receiverA, $receiverB) = $money->allocate([70, 30]);

// outputs 0.04
echo $receiverA;

// outputs 0.01
echo $receiverB;