Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created May 16, 2022 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/57fbfec9435e7dfd1c56fb737b54056a to your computer and use it in GitHub Desktop.
Save kobus1998/57fbfec9435e7dfd1c56fb737b54056a to your computer and use it in GitHub Desktop.
simple calculator
<?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