Created
November 24, 2020 15:24
-
-
Save kobus1998/f41a053e58e9326ebd2febacbefaf30c to your computer and use it in GitHub Desktop.
bc math decimals wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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