Created
September 12, 2013 23:11
-
-
Save mishak87/6545041 to your computer and use it in GitHub Desktop.
This file contains 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 | |
class BcmathCalculator extends Nette\Object implements ICalculator | |
{ | |
/** @var int */ | |
private $scale; | |
/** | |
* @param int | |
*/ | |
public function __construct($scale = 0) | |
{ | |
$this->scale = $scale; | |
} | |
public function getScale() | |
{ | |
return $this->scale; | |
} | |
/* BASIC OPERATIONS */ | |
public function add($a, $b) | |
{ | |
return bcadd($a, $b, $this->scale); | |
} | |
public function subtract($a, $b) | |
{ | |
return bcsub($a, $b, $this->scale); | |
} | |
public function multiply($a, $b) | |
{ | |
return bcmul($a, $b, $this->scale); | |
} | |
public function divide($a, $b) | |
{ | |
return bcdiv($a, $b, $this->scale); | |
} | |
public function power($a, $b) | |
{ | |
return bcpow($a, $b, $this->scale); | |
} | |
/** | |
* @param string|int|float $number | |
* @return string | |
*/ | |
public function floor($number) | |
{ | |
$result = bcmul($number, '1', 0); | |
if ((bccomp($result, '0', 0) == -1) && bccomp($number, $result, 1)) { | |
$result = bcsub($result, 1, 0); | |
} | |
return $result; | |
} | |
/** | |
* @param string|int|float $number | |
* @return string | |
*/ | |
public function ceil($number) | |
{ | |
$floor = $this->bcfloor($number); | |
return bcadd($floor, ceil($this->bcsub($number, $floor)), 0); | |
} | |
/** | |
* @param string|int|float $number | |
* @param int | |
* @return string | |
*/ | |
public function round($number, $decimals = 0) | |
{ | |
if ($decimals < -1) { | |
throw new InvalidArgumentException("Cannot round to negative decimals"); | |
} | |
if ($decimals > 0) { | |
$to = bcpow(10, $decimals, 0); | |
$number = bcmul($number, $to, $this->scale); | |
} | |
$floor = $this->floor($number); | |
$result = bcadd($floor, round(bcsub($number, $floor)), 0); | |
if ($decimals > 0) { | |
$result = bcdiv($floor, $to, $decimals); | |
} | |
return $result; | |
} | |
/* COMPARISON FUNCTIONS */ | |
public function max($a, $b) | |
{ | |
return $this->compare($a, $b) == 1 ? $a : $b; | |
} | |
public function min($a, $b) | |
{ | |
return $this->compare($a, $b) == 1 ? $b : $a; | |
} | |
public function compare($a, $b) | |
{ | |
return bccomp($a, $b, $this->scale); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment