this function spells out numbers in english text.
number to words
conversion.
“number to words” makes use of the built-in PHP functions
is_numeric( ),
fmod( ) and
floor( ).
01 <?php
02
03 $nwords = array(
04 "zero", "one", "two", "three", "four", "five", "six", "seven",
05 "eight", "nine", "ten", "eleven", "twelve", "thirteen",
06 "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
07 "nineteen", "twenty", 30 => "thirty", 40 => "forty",
08 50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty",
09 90 => "ninety"
10 );
11
12 function int_to_words($x)
13 {
14 global $nwords;
15 if(!is_numeric($x))
16 {
17 $w = '#';
18 }else if(fmod($x, 1) != 0)
19 {
20 $w = '#';
21 }else{
22 if($x < 0)
23 {
24 $w = 'minus ';
25 $x = -$x;
26 }else{
27 $w = '';
28 }
29 if($x < 21)
30 {
31 $w .= $nwords[$x];
32 }else if($x < 100)
33 {
34 $w .= $nwords[10 * floor($x/10)];
35 $r = fmod($x, 10);
36 if($r > 0)
37 {
38 $w .= '-'. $nwords[$r];
39 }
40 } else if($x < 1000)
41 {
42 $w .= $nwords[floor($x/100)] .' hundred';
43 $r = fmod($x, 100);
44 if($r > 0)
45 {
46 $w .= ' and '. int_to_words($r);
47 }
48 } else if($x < 1000000)
49 {
50 $w .= int_to_words(floor($x/1000)) .' thousand';
51 $r = fmod($x, 1000);
52 if($r > 0)
53 {
54 $w .= ' ';
55 if($r < 100)
56 {
57 $w .= 'and ';
58 }
59 $w .= int_to_words($r);
60 }
61 } else {
62 $w .= int_to_words(floor($x/1000000)) .' million';
63 $r = fmod($x, 1000000);
64 if($r > 0)
65 {
66 $w .= ' ';
67 if($r < 100)
68 {
69 $word .= 'and ';
70 }
71 $w .= int_to_words($r);
72 }
73 }
74 }
75 return $w;
76 }
77
78 // demonstration
79
80 if(isset($_POST['num']))
81 {
82 echo '
83 <p>the number reads '.int_to_words($_POST['num']).'</p>
84 <p><a href="./">try again</a></p>';
85 }else{
86 echo '
87 <form method="post" action="./">
88 <input type="text" name="num" />
89 <input type="submit" value="spell number" />
90 </form>';
91 }
92
93 ?>