PHP code example of egorsmkv-packagist / decimal

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

    

egorsmkv-packagist / decimal example snippets


use RtLopez\Decimal;

$n1 = Decimal::create(123, 2);
$n2 = Decimal::create(123.45, 2); // not recommended
$n3 = Decimal::create('123.45', 2);
$n4 = Decimal::create($n1, 2);

$number = Decimal::create('12345.671', 2);

echo (string)$number;
// 12345.67

echo $number->format(1, ',', ' ');
// 12 345,7

echo $number->truncate()->format(null, ',', ' ', false);
// 12 345,00

$n1 = Decimal::create('12345.671', 3);
$n2 = Decimal::create('11111.111', 3);
$n3 = $n1->add($n2)->mul(-1);
echo $n3; // -23456.782

// fluid interface
$n4 = $n3->pow(2)->sqrt()->mul(-2)->div(2)->abs();

$n1 = Decimal::create('12345.671', 3);
$n1->add(2);
...
echo $n1;
// 12345.671

$n1 = Decimal::create('12345.671', 3);
$n2 = Decimal::create('11111.111', 3);
$n1->gt($n2);        // true
$n1->eq(0);          // false
$n2->le(100);        // false

$n = Decimal::create('12345.671', 3);
echo $n->round(2);   // 12345.67
echo $n->round(1);   // 12345.7
echo $n->truncate(); // 12345
echo $n->ceil(1);    // 12345.6
echo $n->floor();    // 12346

Decimal::setDefaultImplementation('RtLopez\DecimalBCMath');
Decimal::setDefaultPrecision(6);