Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class DecimalException extends \Exception {}
- // NOTE: math operators (neg, mul, div, sub, add) creates new object for result
- class Decimal implements \JsonSerializable
- {
- const COMPARE_EQUAL = 0;
- const COMPARE_GREATER = 0.1;
- const COMPARE_LESS = -0.1;
- private static $zero;
- /**
- * @var resource GMP Integer
- */
- private $value;
- /**
- * @param int|string $value Value to be converted with GMP.
- * @param int $radix The radix
- *
- * @throws DecimalException If value could not benn converted to GMP resource
- */
- public function __construct($value, $radix = 10)
- {
- $this->value = @gmp_init($value, $radix);
- if (false === $this->value) {
- throw new DecimalException("Wrong value format or type", $value);
- }
- }
- public function isLessThan(Decimal $value)
- {
- return (gmp_cmp($this->value, $value->value) < 0);
- }
- public function isEqualTo(Decimal $value)
- {
- return !gmp_cmp($this->value, $value->value); // == 0
- }
- public function isGreaterThan(Decimal $value)
- {
- return (gmp_cmp($this->value, $value->value) > 0);
- }
- public function isZero()
- {
- return !gmp_intval($this->value); // gmp_intval should be faster than comparison
- }
- public function neg()
- {
- $_ret = new Decimal(0);
- $_ret->value = gmp_neg($this->value);
- return $_ret;
- }
- public function abs()
- {
- $_ret = new Decimal(0);
- $_ret->value = gmp_abs($this->value);
- return $_ret;
- }
- public function add(Decimal $value)
- {
- $_ret = new Decimal(0);
- $_ret->value = gmp_add($this->value, $value->value);
- return $_ret;
- }
- public function sub(Decimal $value)
- {
- $_ret = new Decimal(0);
- $_ret->value = gmp_sub($this->value, $value->value);
- return $_ret;
- }
- public function mul(Decimal $value)
- {
- $_ret = new Decimal(0);
- $_ret->value = gmp_mul($this->value, $value->value);
- return $_ret;
- }
- public function div(Decimal $value, $round = GMP_ROUND_ZERO)
- {
- $_ret = new Decimal(0);
- $_ret->value = gmp_div_q($this->value, $value->value, $round);
- return $_ret;
- }
- // public function div_r(Decimal $value)
- // {
- // $_ret = new Decimal(0);
- //
- // $_ret->value = gmp_div_r($this->value, $value->value);
- //
- // return $_ret;
- // }
- public function __toString()
- {
- return gmp_strval($this->value);
- }
- public static function zero()
- {
- if (!self::$zero) {
- self::$zero = new Decimal(0);
- }
- return self::$zero;
- }
- public function jsonSerialize()
- {
- return (string)$this;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement