![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Hobbyist Programmer
Join Date: Apr 2005
Posts: 126
Rep Power: 4
![]() |
Number to Word
Im trying to write a script to change a number like 1003 to a word, One Thousand Three (No and, and the number has no commas (php can add them in anyways))
Im trying to design the script as small as possible, just into one function, but I cant figure out how to do it, my first idea was to do this: Add in the commas, then explode into sections, then use the plain number in each position, and then add on the appropriate ending, but my coding was so messed up the variables and arrays ended up being things like $wor[$pos[$sec[$i]]] and thats so messed up... i couldnt ever get it working, any better ideas? |
|
|
|
|
|
#2 |
|
Programming Guru
![]() |
Sounds like fun, i'll give it a shot...
__________________
|
|
|
|
|
|
#3 |
|
Programming Guru
![]() |
Found this on php.net somewhere:
[php]<?php $nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", 30 => "thirty", 40 => "forty", 50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty", 90 => "ninety" ); function int_to_words($x) { global $nwords; if(!is_numeric($x)) $w = '#'; else if(fmod($x, 1) != 0) $w = '#'; else { if($x < 0) { $w = 'minus '; $x = -$x; } else $w = ''; // ... now $x is a non-negative integer. if($x < 21) // 0 to 20 $w .= $nwords[$x]; else if($x < 100) { // 21 to 99 $w .= $nwords[10 * floor($x/10)]; $r = fmod($x, 10); if($r > 0) $w .= '-'. $nwords[$r]; } else if($x < 1000) { // 100 to 999 $w .= $nwords[floor($x/100)] .' hundred'; $r = fmod($x, 100); if($r > 0) $w .= ' and '. int_to_words($r); } else if($x < 1000000) { // 1000 to 999999 $w .= int_to_words(floor($x/1000)) .' thousand'; $r = fmod($x, 1000); if($r > 0) { $w .= ' '; if($r < 100) $w .= 'and '; $w .= int_to_words($r); } } else { // millions $w .= int_to_words(floor($x/1000000)) .' million'; $r = fmod($x, 1000000); if($r > 0) { $w .= ' '; if($r < 100) $word .= 'and '; $w .= int_to_words($r); } } } return $w; } ?> Usage: <?php echo 'There are currently '. int_to_words(10029) . ' members logged on.'; ?>[/php]
__________________
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|