Re: number to word converter

From: Date: Fri, 31 Aug 2001 12:03:06 +0000
Subject: Re: number to word converter
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-65454@lists.php.net to get a copy of this message
<Original message> From: Carry Ian <carry@bharatnet.com> Date: Fri, Aug 31, 2001 at 12:36:20PM +0200 Message-ID: <200108311036.f7VAaJS17568@datalink.telemediair.nl> Subject: [PHP] number to word converter > Hello, > > can anybody suggest me where could i get a script to convert a integer value to a phrase. > for eg. "135" to "One Hundred And Thirty Five" > > thanks in advance. > > carry </Original message> <Reply> In some spare time I just created this function. It's prob. far from optimal, so maybe you'll have to give a look in order to optimize it. But at least it works. --- PHP code --- <? function inttoword ($x) { settype ($x, "string"); $returnString = ""; $digit = array ("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"); $tens = array ("Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"); $hundred = false; for ($pos = 0; $pos < strlen ($x); $pos++) { $togo = strlen($x)-$pos; $returnString .= " "; if ($togo > 2) { if ($togo > 3) { $returnString .= inttoword (substr($x, 0, $togo-3)); $returnString .= " Thousand"; $pos += ($togo-4); } else { if ((integer)substr($x, $pos, 1) > 0) { $returnString .= $digit[((integer)substr($x, $pos, 1))-1]; $returnString .= " Hundred"; $hundred = true; } } } elseif ($togo == 2) { if ((integer)substr($x, $pos, 1) == 1) { if ($hundred) $returnString .= "and "; $returnString .= $digit[((integer)substr($x, $pos, 2))-1]; break; } else { if ((integer)substr($x, $pos, 1) > 0) { if ($hundred) $returnString .= "and "; $hundred = false; $returnString .= $tens[((integer)substr($x, $pos, 1))-2]; } $pos++; $returnString .= " "; if ((integer)substr($x, $pos, 1)) { if ($hundred) $returnString .= "and "; $returnString .= $digit[((integer)substr($x, $pos, 1))-1]; } break; } } else { if ($hundred) $returnString .= "and "; $returnString .= $digit[((integer)substr($x, $pos, 1))-1]; } } return (preg_replace ("/\s+/", " ", preg_replace ("/^\s+/", "", $returnString))); } ?> <PRE> <? print inttoword(11)."\n"; print inttoword(21)."\n"; print inttoword(101)."\n"; print inttoword(152)."\n"; print inttoword(1000)."\n"; print inttoword(101032)."\n"; print inttoword(111111)."\n"; ?> </PRE> --- End of PHP code --- Let me know if this is what you're looking for and/or if you have optimized it. Good luck! </Reply> -- * R&zE: -- »»»»»»»»»»»»»»»»»»»»»»»» -- Renze Munnik -- DataLink BV -- -- E: renze@datalink.nl -- W: +31 23 5326162 -- F: +31 23 5322144 -- M: +31 6 21811143 -- -- Stationsplein 82 -- 2011 LM HAARLEM -- Netherlands -- -- http://www.datalink.nl -- ««««««««««««««««««««««««

« previous php.general (#65454) next »