PHP code example of fab2s / math

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

    

fab2s / math example snippets


// instance way
$number = new Math('42');

// fluent grammar
$result = (string) $number->add('1')->sub(2)->div(1)->add(1)->mul(-1); // '-42'

// factory way: number
$result = (string) Math::number('42')->add('1')->sub(2)->div('1')->add(1)->mul(-1); // '-42'

// factory way: fromBase
$result = (string) Math::fromBase('LZ', 62); // '1337'
$result = (string) Math::fromBase('LZ', 62)->sub(1295); // '42'

// combos
$number = Math::number('42')
    ->add(Math::fromBase('LZ', 62), '-42')
    ->sub('1337', '42')
    ->mul(3, 4, 1)
    ->div(4, 3)
    ->sub('.1')
    ->abs()
    ->round(0)
    ->floor()
    ->ceil()
    ->min('512', '256')
    ->max('8', '16', '32');

// formatting does not mutate internal number
$result = (string) $number->format(2); // '42.00'
$result = (string) $number; // '42';
// and you can continue calculating after string cast
$result = (string) $number->add('1295')->toBase(62); // 'LZ'

// toBase does not mutate base 10 internal representation
$result = (string) $number; // '1337';

$result = (string) Math::number('0000042.000000'); // '42'

// raw form
$result = Math::number('0000042.000000')->getNumber(); // '0000042.000000'

// with some tolerance
$result = Math::number('  42.0000 ')->getNumber(); // '42.0000'

// at all time
if ((string) $number1 === (string) $number2) {
    // both instance numbers are equals
}

// same as (internally using bccomp)
if ($number1->eq($number2)) {
    // both instance numbers are equals
}

$number = new Math('42');
// same as
$number = Math::number('42');

// in constructor
$result = (string) (new Math($number))->div('2'); // '21'
// same as
$result = (string) Math::number($number)->div('2'); // '21'

// in calc method
$result = (string) Math::number('42')->add($number)->sub('42')->div('2'); // '21'

// set global precision
Math::setGlobalPrecision(18);

$number = (new Math('100'))->div('3'); // uses precision 18
$number->setPrecision(14); // will use precision 14 for any further calculations

use fab2s\Math\Laravel\MathCast;

class MyModel extends Model
{
    protected $casts   = [
        'not_nullable' => MathCast::class,
        'nullable'     => MathCast::class . ':nullable',
    ];
}

$model = new MyModel;

$model->not_nullable = 41;
$model->not_nullable->add(1)->eq(42); // true

$model->not_nullable = null; // throw a NotNullableException

$model->nullabe = null; // is ok