3v4l.org

run code in 300+ PHP versions simultaneously
<?php class BigDecimal { private $value; private $scale; function __construct(string $value){ if(preg_match('@^[0-9]*(?:.[0-9]*)?$@', $value) !== 1){ throw new Error("Invalid BigDecimal value $value"); } $this->value = $value; $this->scale = $this->getScaleOf($value); } private function getScale(BigDecimal $other){ return max($this->scale, $other->scale); } private function getScaleOf(string $value){ $pos = strrpos($value, '.'); if($pos === false){ return 0; } return strlen($value) - $pos - 1; } function compareTo($other){ return bccomp($this, $other, $this->getScale($other)); } function gt($other){ return $this->compareTo($other) > 0; } function gte($other){ return $this->compareTo($other) >= 0; } function lt($other){ return $this->compareTo($other) < 0; } function lte($other){ return $this->compareTo($other) <= 0; } function eq($other){ return $this->compareTo($other) === 0; } function add(BigDecimal $other){ return new self(bcadd($this, $other, $this->getScale($other))); } function div(BigDecimal $other){ return new self(bcdiv($this, $other, $this->getScale($other))); } function mod(BigDecimal $other){ // not sure if mod or rem return new self(bcmod($this, $other, $this->getScale($other))); } function mul(BigDecimal $other){ return new self(bcmul($this, $other, $this->getScale($other))); } function pow(BigDecimal $other){ return new self(bcpow($this, $other, $this->getScale($other))); } function sub(BigDecimal $other){ return new self(bcsub($this, $other, $this->getScale($other))); } function __toString(){ return $this->value; } } function d(string $value){ return new BigDecimal($value); } echo d('10.123')->sub(d('5.02')) . "\n"; echo d('10')->sub(d('5')) . "\n"; var_dump(d('10.12345678')->gt(d('10.1234567777777777777777777777777'))); var_dump(d('10.12345678')->gt(d('10.1234567800000000000000000000000000001'))); // false var_dump(d('10.12345678')->gte(d('10.123456780000000000000000000'))); // true
Output for 7.3.32 - 7.3.33, 7.4.33, 8.0.13, 8.5.1 - 8.5.3
Fatal error: Uncaught Error: Call to undefined function bcsub() in /in/H6N1d:71 Stack trace: #0 /in/H6N1d(83): BigDecimal->sub(Object(BigDecimal)) #1 {main} thrown in /in/H6N1d on line 71
Process exited with code 255.
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.6 - 7.2.33, 7.3.16 - 7.3.31, 7.4.0 - 7.4.32, 8.0.0 - 8.0.12, 8.0.14 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0
5.103 5 bool(true) bool(false) bool(true)
Output for 5.6.0 - 5.6.28
Catchable fatal error: Argument 1 passed to d() must be an instance of string, string given, called in /in/H6N1d on line 83 and defined in /in/H6N1d on line 79
Process exited with code 255.

preferences:
100.64 ms | 1522 KiB | 4 Q