Created
May 16, 2022 14:50
-
-
Save kobus1998/57fbfec9435e7dfd1c56fb737b54056a to your computer and use it in GitHub Desktop.
simple calculator
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 | |
(new class { | |
const SCALE = 14; | |
public function __invoke() | |
{ | |
while(true) { | |
$i = $this->parseFloat(readline("number: ")); | |
$operator = trim(readline("operator: ")); | |
$i2 = $this->parseFloat(readline("number: ")); | |
$fResult = $this->calculate($i, $operator, $i2); | |
$sSum = is_numeric($fResult) ? "{$i} {$operator} {$i2} = " : ''; | |
$this->clr(); | |
echo sprintf("answer: %s%s\n\n", $sSum, is_numeric($fResult) ? number_format($fResult, 2) : $fResult); | |
} | |
} | |
/** | |
* parse | |
* | |
* @param string $i | |
* @return string | |
*/ | |
public function parseFloat($i) | |
{ | |
return str_replace(',', '.', trim($i)); | |
} | |
/** | |
* do calculation | |
* | |
* @param int|float $i | |
* @param string $op | |
* @param int|float $i2 | |
* @return string | |
*/ | |
public function calculate($i, $op, $i2) | |
{ | |
switch ($op) { | |
case '+': | |
return round(bcadd($i, $i2, self::SCALE), 2); | |
case '*': | |
return round(bcmul($i, $i2, self::SCALE), 2); | |
case '-': | |
return round(bcsub($i, $i2, self::SCALE), 2); | |
case '/': | |
if ($i2 == 0) { | |
return 'can\'t divide zero'; | |
} | |
return round(bcdiv($i, $i2, self::SCALE), 2); | |
case '^': | |
return round(pow($i, $i2), 2); | |
default: | |
return "{$op} not supported"; | |
} | |
} | |
/** @return self */ | |
public function clr() | |
{ | |
echo chr(27).chr(91).'H'.chr(27).chr(91).'J'; | |
return $this; | |
} | |
})(); | |
die("\n"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment