PHP code example of piggly / php-decimal

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

    

piggly / php-decimal example snippets


$w = new Decimal(123);
$x = new Decimal(123.4567);
$y = new Decimal('123456.7e-3');
$z = new Decimal($x);

$w = new Decimal('0xff.f');		// '255.9375'
$x = new Decimal('0b10101100');	// '172'

$x = new Decimal(0.3);

$x->minus(0.1);						// $x is still 0.3
$y = $x->minus(0.1)->minus(0.1);	// $x is still 0.3 and $y is 0.1

$x->dividedBy($y)->plus($z)->times(9)->floor();
$x->times('1.23456780123456789e+9')->plus(9876.5432321)->dividedBy('4444562598.111772')->ceil();

$x->squareRoot()->dividedBy($y)->toPower(3)->equals($x->sqrt()->div($y)->pow(3))	// true
$x->cmp($y->mod($z)->neg()) == 1 && x->comparedTo($y->modulo($z)->negated()) == 1	// true

$x = new Decimal(255.5);

$x->toExponential(5)  // '2.55500e+2'
$x->toFixed(5)        // '255.50000'
$x->toPrecision(5)    // '255.50'
$x->valueOf()         // '255.5'

Decimal::sqrtOf('6.98372465832e+9823')      // '8.3568682281821340204e+4911'
Decimal::powOf(2, 0.0979843)                // '1.0702770511687781839'

$x = new Decimal(INF);     // INF
$y = new Decimal(NAN);     // NAN

$x->isCountless()    // If it is INF or NAN
$x->isFinite()       // If it is a finite number
$x->isInfinite()     // If it is an infinite number
$x->isInt()          // If it is an integer
$x->isNaN()          // If it is NAN
$x->isNegative()     // If it is negative
$x->isNulled()       // If it is INF, NAN or Zero
$x->isPositive()     // If it is positive
$x->isZero()         // If it is zero

$z = new Decimal(355);
$pi = $z->dividedBy(113);        // '3->1415929204'
$pi->toFraction();               // [ '7853982301', '2500000000' ]
$pi->toFraction(1000);           // [ '355', '113' ]

// Set the precision and rounding of the global instance, 
// applies to all Decimal objects without configurations attached to it.
DecimalConfig::instance()->set([ 'precision' => 5, 'rounding' => 4 ]);

$decimal9 = DecimalConfig::clone()->set([ 'precision' => 9, 'rounding' => 1 ]);

$x = new Decimal(5);
$y = new Decimal(5, $decimal9);

$x->div(3);     // '1.6667'
$y->div(3);     // '1.66666666'

// $decimal9 applies to all `Decimal` numbers 
// created from $y in this case
$y->div(3)->times(1.5) // '2.50000000'

$x = new Decimal(-12345.67);

$x->getDigits();          // [ 12345, 6700000 ]    digits (base 10000000)
$x->getExponent();        // 4                     exponent (base 10)
$x->getSign();            // -1                    sign