Re[4]: [PHP] numeric to word function

From: Date: Thu, 19 Sep 2002 02:42:10 +0000
Subject: Re[4]: [PHP] numeric to word function
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-116833@lists.php.net to get a copy of this message
Hi, Thursday, September 19, 2002, 5:29:06 AM, you wrote: BY> What does this do? Here is the class again with all errors fixed and some unfinished bits but it should be enough to get you started. It uses recursion as it repeats after one thousand .. ie one, two, three .... one thousand, two thousand, three thousand... class num_to_text { var $mode; //NUMERIC CURRENCY var $words = array(0=>array('zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty'), 1=>array('zero','one','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'), 2=>array('thousand','million')); var $money = array(0=>array('Dollar','Dollars'), 1=>array('Cent','Cents')); function num_class($mode = 'NUMERIC'){ $this->mode = $mode; } function convert($num){ return $this->num($num,1); } function num($num,$key = 0){ static $t; static $call; $res = intval($num/100); $left = $num%100; if($key == 1){ //first non recursive call reset text and thousand/million toggle $t = ""; $call = 0; } else{ // do we need to print thousand as this is a recursive call if($num%1000 > 0)$t = ' '.$this->words[2][$call].' '.$t; $call ^= 1; //toggle call for next recursion } if($left <= 20){ // no need to split it if($left == 0){ // is the whole mess just zero if($res == 0) $t = $this->words[0][$left].$t; } else{ $t = $this->words[0][$left].$t; } } else{ //need to split it up $tens = intval($left/10); $units = $left%10; ($units > 0)? $units = ' '.$this->words[0][$units] : $units = ''; // eg thirty or thirty one $t = $this->words[1][$tens].$units.$t; } if($res < 10){ if($res > 0){ ($left == 0)? $and = '':$and = ' and '; // do we need to print 'and' if($res > 0) $t = $this->words[0][$res]. " hundred".$and.$t; } } else{ $res = $res%10; if($res > 0){ ($left == 0)? $and = '':$and = ' and '; $t = $this->words[0][$res]. " hundred".$and.$t; } else{ if($left > 0)$t = ' and '.$t; } $num = intval($num/1000); $this->num($num); } return $t; } } //usage $n2t = new num_to_text(); for($num = 0;$num < 11;$num++){ echo $num.' '.$n2t->convert($num).'<br>'; } -- regards, Tom

« previous php.general (#116833) next »