1. Go to this page and download the library: Download andkom/php-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/ */
andkom / php-decimal example snippets
use AndKom\Decimal;
use AndKom\DecimalImmutable;
// Create from various types
$a = new Decimal('1.5', 2);
$b = Decimal::create(2);
$c = Decimal::createFromFloat(3.14, 2);
// Arithmetic (mutable - modifies in place)
$result = (new Decimal('10', 2))->add('3.5')->multiply('2');
echo $result->getValue(); // '27.00'
// Immutable - always returns a new instance
$price = new DecimalImmutable('19.99', 2);
$discounted = $price->multiply('0.9');
echo $price->getValue(); // '19.99' (unchanged)
echo $discounted->getValue(); // '17.99'
// Rounding
echo (new Decimal('2.5', 1))->roundHalfUp()->getValue(); // '3'
echo (new Decimal('2.5', 1))->roundHalfEven()->getValue(); // '2'
// Formatting
echo (new Decimal('1234567.89', 2))->toFormat(2); // '1,234,567.89'
echo (new Decimal('1.5', 1))->toScientific(2); // '1.5E0'
echo (new Decimal('1.234', 3))->toFixed(2); // '1.23'
// Comparisons
$a = new Decimal('1.5', 1);
$a->isGreaterThan('1'); // true
$a->isEqual('1.5'); // true
$a->isPositive(); // true
Decimal::setDefaultScale(4);
echo (new Decimal('1'))->getValue(); // '1.0000'
echo Decimal::getDefaultScale(); // 4
echo (new Decimal('10', 2))->divide('3', 4)->getValue(); // '3.3333'
echo (new Decimal('2'))->power(-3, 3)->getValue(); // '0.125'
echo (new Decimal('2'))->squareRoot(4)->getValue(); // '1.4142'
echo (new Decimal('2.5', 1))->roundHalfUp()->getValue(); // '3'
echo (new Decimal('2.5', 1))->roundHalfDown()->getValue(); // '2'
echo (new Decimal('2.5', 1))->roundHalfEven()->getValue(); // '2'
echo (new Decimal('3.5', 1))->roundHalfEven()->getValue(); // '4'
echo (new Decimal('-2.1', 1))->roundUp()->getValue(); // '-3'
echo (new Decimal('-2.1', 1))->ceil()->getValue(); // '-2'
echo (new Decimal('-2.1', 1))->floor()->getValue(); // '-3'
echo (new Decimal('123'))->round(-1)->getValue(); // '120'
echo (new Decimal('-5'))->inverse()->getValue(); // '5'
echo (new Decimal('5'))->inverse()->getValue(); // '-5'
echo (new Decimal('5'))->negate()->getValue(); // '-5'
echo (new Decimal('-5'))->negate()->getValue(); // '-5'
echo (new Decimal('-5'))->absolutize()->getValue(); // '5'