Guest User

Untitled

a guest
Jul 21st, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. class Extenso
  2. {
  3. // Types
  4. const MONEY = 1;
  5. const INTEGER = 2;
  6.  
  7. // Variables
  8. public $amount;
  9. private $type;
  10.  
  11. public function __construct($amount = 0, $type = self::INTEGER)
  12. {
  13. $this->type = $type;
  14.  
  15. switch ($type) {
  16. case self::MONEY:
  17. $amount = (float) $amount;
  18. $this->amount = array(
  19. "reais" => intval($amount),
  20. "centavos" => intval($amount * 100) % 100
  21. );
  22.  
  23. break;
  24. default:
  25. $this->amount = (int) $amount;
  26. }
  27. }
  28.  
  29. // classes numéricas
  30. private function get_classes($amount)
  31. {
  32. $class = [];
  33.  
  34. $total = floor(floor(log($amount, 10))/3)+1;
  35.  
  36. for ($i=1;$i<=$total;$i++) {
  37. $class[$i-1] = $amount % pow(10, 3*$i) - array_sum($class);
  38. }
  39.  
  40. return $class;
  41. }
  42.  
  43. private function print($value)
  44. {
  45. $f = new NumberFormatter("pt-BR", NumberFormatter::SPELLOUT);
  46. return $f->format($value);
  47. }
  48.  
  49. private function join(&$str, $classes, $i)
  50. {
  51. if(!($classes[$i-1] % pow(10, 3*$i-1)))
  52. $str .= " e ";
  53. elseif($classes[$i-1] < pow(10, 3*$i-1))
  54. $str .= " e ";
  55. else
  56. $str .= ", ";
  57. }
  58.  
  59. private function formatting($amount)
  60. {
  61. $str = null;
  62.  
  63. $classes = $this->get_classes($amount);
  64.  
  65. for ($i=count($classes)-1;$i>0;$i--) {
  66. $value = $classes[$i];
  67.  
  68. if(!$value) continue;
  69.  
  70. $str .= $this->print($value);
  71.  
  72. $this->join($str, $classes, $i);
  73. }
  74.  
  75. if (($classes[0])) {
  76. $str .= $this->print($classes[0]);
  77. } else {
  78. $str = trim(substr($str, 0, -2));
  79. }
  80.  
  81. return $str;
  82. }
  83.  
  84. public function __toString()
  85. {
  86. if ($this->type == self::MONEY) {
  87. $amount = $this->amount['reais'];
  88. } else {
  89. $amount = $this->amount;
  90. }
  91.  
  92. $str = $this->formatting($amount) . " reais";
  93.  
  94. if ($this->amount['centavos'] > 0)
  95. $str .= " e " . $this->formatting($this->amount['centavos']) . " centavos";
  96.  
  97. return $str;
  98. }
  99. }
Add Comment
Please, Sign In to add comment