Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Extenso
- {
- // Types
- const MONEY = 1;
- const INTEGER = 2;
- // Variables
- public $amount;
- private $type;
- public function __construct($amount = 0, $type = self::INTEGER)
- {
- $this->type = $type;
- switch ($type) {
- case self::MONEY:
- $amount = (float) $amount;
- $this->amount = array(
- "reais" => intval($amount),
- "centavos" => intval($amount * 100) % 100
- );
- break;
- default:
- $this->amount = (int) $amount;
- }
- }
- // classes numéricas
- private function get_classes($amount)
- {
- $class = [];
- $total = floor(floor(log($amount, 10))/3)+1;
- for ($i=1;$i<=$total;$i++) {
- $class[$i-1] = $amount % pow(10, 3*$i) - array_sum($class);
- }
- return $class;
- }
- private function print($value)
- {
- $f = new NumberFormatter("pt-BR", NumberFormatter::SPELLOUT);
- return $f->format($value);
- }
- private function join(&$str, $classes, $i)
- {
- if(!($classes[$i-1] % pow(10, 3*$i-1)))
- $str .= " e ";
- elseif($classes[$i-1] < pow(10, 3*$i-1))
- $str .= " e ";
- else
- $str .= ", ";
- }
- private function formatting($amount)
- {
- $str = null;
- $classes = $this->get_classes($amount);
- for ($i=count($classes)-1;$i>0;$i--) {
- $value = $classes[$i];
- if(!$value) continue;
- $str .= $this->print($value);
- $this->join($str, $classes, $i);
- }
- if (($classes[0])) {
- $str .= $this->print($classes[0]);
- } else {
- $str = trim(substr($str, 0, -2));
- }
- return $str;
- }
- public function __toString()
- {
- if ($this->type == self::MONEY) {
- $amount = $this->amount['reais'];
- } else {
- $amount = $this->amount;
- }
- $str = $this->formatting($amount) . " reais";
- if ($this->amount['centavos'] > 0)
- $str .= " e " . $this->formatting($this->amount['centavos']) . " centavos";
- return $str;
- }
- }
Add Comment
Please, Sign In to add comment