PHP code example of jimeneztdavid / scaled-int-laravel

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

    

jimeneztdavid / scaled-int-laravel example snippets


var_dump(0.1 + 0.2); // float(0.30000000000000004)
var_dump((0.1 + 0.2) === 0.3); // bool(false)

public function setPriceAttribute($value): void
{
    $this->attributes['price'] = (int) round($value * 100);
}

public function getPriceAttribute($value): float
{
    return $value / 100;
}

var_dump(0.3 === (0.1 + 0.2)); // bool(false)

use Jimeneztdavid\ScaledInt\ScaledInt;

$a = ScaledInt::fromMajor('0.10');
$b = ScaledInt::fromMajor('0.20');

echo $a->add($b); // 0.30

$product->price = 10.25;
$product->save();

// save as 1025
// read back as 10.25

use Jimeneztdavid\ScaledIntLaravel\ScaledIntCast;

protected function casts(): array
{
    return [
        'price' => ScaledIntCast::class.':100',
    ];
}

use Jimeneztdavid\ScaledIntLaravel\ScaledIntCast;

protected function casts(): array
{
    return [
        'price' => ScaledIntCast::class.':100',
    ];
}

$product = new Product();
$product->price = '10.25';
$product->save();

// database value: 1025
echo $product->price; // 10.25

use Jimeneztdavid\ScaledInt\ScaledInt;

$price = ScaledInt::fromMajor('10.25');
$weight = ScaledInt::fromMajor('2.750', 1000);
$minor = ScaledInt::fromMinor(1025);

echo $price; // 10.25
echo $weight; // 2.750
echo $minor; // 10.25

echo $price->minor(); // 1025
echo $price->scale(); // 100
echo $price->toMajorString(); // 10.25
echo $price; // 10.25

$price = ScaledInt::fromMajor('100.00');
$tax = ScaledInt::fromMajor('19.00');
$discount = ScaledInt::fromMajor('15.00');

$price->add($tax); // 119.00
$price->subtract($discount); // 85.00
$price->multiplyByInt(2); // 200.00
$price->divideByIntExact(2); // 50.00
$price->divideByInt(3, \Jimeneztdavid\ScaledInt\RoundingMode::HALF_UP); // 33.33
$price->percentOf(19, \Jimeneztdavid\ScaledInt\RoundingMode::HALF_UP); // 19.00

$price = ScaledInt::fromMajor('10.25');
$other = ScaledInt::fromMajor('10.30');
$min = ScaledInt::fromMajor('10.00');
$max = ScaledInt::fromMajor('20.00');

$price->compareTo($other); // -1
$other->compareTo($price); // 1
$price->min($other); // 10.25
$price->max($other); // 10.30
$price->between($min, $max); // true

$product->price = '10.25'; // stored as 1025
$product->price = \Jimeneztdavid\ScaledInt\ScaledInt::fromMajor('10.25', 100); // stored as 1025
$product->price = 1025; // read back as 10.25
$product->price = null; // stored as null
bash
php artisan vendor:publish --tag=scaled-int-config