<?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);
echo "scale of $value is " . $this->scale . "\n";
}
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;
}
function valueEquals($other){
}
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'));
scale of 10.123 is 4
scale of 5.02 is 3
scale of 5.1030 is 5
5.1030
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
scale of 10.123 is 4
scale of 5.02 is 3
scale of 5.1030 is 5
5.1030
Output for 7.3.32 - 7.3.33, 7.4.33, 8.0.13
scale of 10.123 is 4
scale of 5.02 is 3
Fatal error: Uncaught Error: Call to undefined function bcsub() in /in/mIH01:53
Stack trace:
#0 /in/mIH01(65): BigDecimal->sub(Object(BigDecimal))
#1 {main}
thrown in /in/mIH01 on line 53
Process exited with code 255.
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/mIH01 on line 65 and defined in /in/mIH01 on line 61
Process exited with code 255.