PHP code example of webgriffe / rational

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

    

webgriffe / rational example snippets


use Webgriffe\Rational;

//Creates a zero value
$r0 = Rational::zero();

//Creates a one value
$r1 = Rational::one();

//Creates a whole number
$r2 = Rational::fromWhole(-2);

//Creates a variable that stores exactly ⅔ (two thirds), roughly 0.666666...
$r3 = Rational::fromFraction(2, 3);

//Creates a variable that stores exactly 4 + ⅑ (one ninth), roughly 7.111111...
$r4 = Rational::fromWholeAndFraction(4, 1, 9);

//Adds $r1 and $r2 so that $r5 equals -1
$r5 = $r1->add($r2);

//Adds $r3 to $r5: -1 + ⅔ = -⅓
$r6 = $r5->add($r3);

//Subtracts $r6 from $r2: -2 - (-⅓) = -2 + ⅓ = -1 - ⅔
$r7 = $r2->sub($r6);

//Multiply $r7 by $r4: (-1 - ⅔) * (4 + ⅑)
//= -4 - 1/9 - 8/3 - 2/27
//= -4 - 3/27 - 72/27 - 2/27
//= -4 - 77/27
//= -4 - 2 - 23/27
//= -6 - 23/27
$r8 = $r7->mul($r4);

//Divide $r8 by $r3: (-6 - 23/27) / (2/3)
//= (-6 - 23/27) * (3/2)
//= -9 - 23/18
//= -9 - 1 - 5/18
//= -10 - 5/18
$r9 = $r8->div($r3);

//Compute the reciprocal of $r9: 1/(-10 - 5/18)
//= 1/((-180 - 5)/18)
//= 1/(-185/18)
//= 18/-185
//= -18/185
$r10 = $r9->recip();

//$r11 = $r10 + $r1: -18/185 + 1
//= -18/185 + 185/185
//= 167/185
$r11 = $r10->add($r1);

//Prints 0,903
echo $r11->format(3, 0, ',', '');

//Forces 2 decimals and prints 0.90. Useful when dealing with prices
echo $r11->format(2, 2, '.', '');

//$r12 = $r11 - $r10: 167/185 - (-18/185)
//= 167/185 + 18/185
//= 185/185
//= 1
$r12 = $r11->sub($r10);

use Webgriffe\Rational;

final class Money extends Rational {
}

use Webgriffe\Rational;

class Money {
    public function __construct(
        private readonly Rational $value
    ) {
    }

    public function add(self $other): static {
        return new static($this->value->add($other->value));
    }
    
    ...
}

$ php composer.phar install