Last active
October 8, 2019 10:13
-
-
Save zavodnoyapl1992/cc6d0ca2755df20eb9a6c6a75e2e18ad to your computer and use it in GitHub Desktop.
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
class Number { | |
private $precision; | |
private $int; | |
public function __construct($number) | |
{ | |
$this->precision = (int)$this->getPrecision($number); | |
$this->int = pow(10, $this->precision) * $number; | |
} | |
public function add($number) | |
{ | |
$precision = $this->getPrecision($number); | |
$this->updatePrecision($precision); | |
$this->int = (int)($this->int + pow(10, $this->precision) * $number); | |
} | |
public function subtract($number) | |
{ | |
$precision = $this->getPrecision($number); | |
$this->updatePrecision($precision); | |
$this->int = (int)($this->int - pow(10, $this->precision) * $number); | |
} | |
public function getNumber() | |
{ | |
return $this->int/pow(10, $this->precision); | |
} | |
private function getPrecision($number) | |
{ | |
$list = explode('.', (string)$number); | |
if (empty($list[1])) { | |
return 0; | |
} | |
return strlen((string)$list[1]); | |
} | |
private function updatePrecision($precision) | |
{ | |
if ($this->precision >= $precision) { | |
return; | |
} | |
$this->int = (int)($this->int * pow(10, ($precision - $this->precision))); | |
$this->precision = $precision; | |
} | |
} | |
for ($i = new Number(0); $i->getNumber() <= 1; $i->add(0.1)) { | |
echo (int)($i->getNumber() * 10) . PHP_EOL; | |
} | |
for ($i = 0; $i <= 1; $i += 0.1) { | |
echo (int)($i*10) . PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment