Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created November 24, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/f41a053e58e9326ebd2febacbefaf30c to your computer and use it in GitHub Desktop.
Save kobus1998/f41a053e58e9326ebd2febacbefaf30c to your computer and use it in GitHub Desktop.
bc math decimals wrapper
<?php
declare(strict_types=1);
/**
* wrapper around the bcdec extension
*
* @see https://www.php.net/manual/en/book.bc.php
*/
class Bcdec
{
/** @var float */
protected $fNumber;
/** @var int */
protected $iDecimals;
/**
* constuct
*
* @param float $fNumber
* @param int $iDecimals
*/
public function __construct($fNumber, int $iDecimals = 9)
{
$this->fNumber = (string) $fNumber;
$this->iDecimals = $iDecimals;
}
/**
* Add two arbitrary precision numbers
*
* @param float $fNum
* @return self
*/
public function add($fNum): self
{
$fNum = (string) $fNum;
$this->fNumber = bcadd($this->fNumber, $fNum, $this->iDecimals);
return $this;
}
/**
* Subtract one arbitrary precision number from another
*
* @param float $fNum
* @return self
*/
public function subtract($fNum): self
{
$fNum = (string) $fNum;
$this->fNumber = bcsub($this->fNumber, $fNum, $this->iDecimals);
return $this;
}
/**
* Divide two arbitrary precision numbers
*
* @param float $fNum
* @return self
*/
public function divide($fNum)
{
$fNum = (string) $fNum;
if ($fNum != 0) {
$this->fNumber = bcdiv($this->fNumber, $fNum, $this->iDecimals);
}
return $this;
}
/**
* Multiply two arbitrary precision numbers
*
* @param float $fNum
* @return self
*/
public function multiply($fNum): self
{
$fNum = (string) $fNum;
$this->fNumber = bcmul($this->fNumber, $fNum, $this->iDecimals);
return $this;
}
/**
* get the result
*
* @return float
*/
public function get(): string
{
return $this->fNumber;
}
/**
* to string
*
* @return string
*/
public function __toString(): string
{
return (string) $this->get();
}
}
<?php
declare(strict_types=1);
$dec = (new Bcdec(1.2, 2))
->add(1.4)
->multiply(2)
->subtract(1)
->add(64.8);
echo (string) $dec; // 69.00, nice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment