Posted By

adkatrit on 02/21/10


Tagged

number convertconversion


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

adkatrit


Number to word converter "1->one" up to the million place


 / Published in: PHP
 

this could be expanded to the billions place, but c'mon really people? it's got to call it quits somewhere

  1. <?php
  2.  
  3. $nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven",
  4. "eight", "nine", "ten", "eleven", "twelve", "thirteen",
  5. "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
  6. "nineteen", "twenty", 30 => "thirty", 40 => "forty",
  7. 50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty",
  8. 90 => "ninety" );
  9.  
  10. function int_to_words($x)
  11. {
  12. global $nwords;
  13. if(!is_numeric($x))
  14. {
  15. $w = '#';
  16. }else if(fmod($x, 1) != 0)
  17. {
  18. $w = '#';
  19. }else{
  20. if($x < 0)
  21. {
  22. $w = 'minus ';
  23. $x = -$x;
  24. }else{
  25. $w = '';
  26. }
  27. if($x < 21)
  28. {
  29. $w .= $nwords[$x];
  30. }else if($x < 100)
  31. {
  32. $w .= $nwords[10 * floor($x/10)];
  33. $r = fmod($x, 10);
  34. if($r > 0)
  35. {
  36. $w .= '-'. $nwords[$r];
  37. }
  38. } else if($x < 1000)
  39. {
  40. $w .= $nwords[floor($x/100)] .' hundred';
  41. $r = fmod($x, 100);
  42. if($r > 0)
  43. {
  44. $w .= ' and '. int_to_words($r);
  45. }
  46. } else if($x < 1000000)
  47. {
  48. $w .= int_to_words(floor($x/1000)) .' thousand';
  49. $r = fmod($x, 1000);
  50. if($r > 0)
  51. {
  52. $w .= ' ';
  53. if($r < 100)
  54. {
  55. $w .= 'and';
  56. }
  57. $w .= int_to_words($r);
  58. }
  59. } else {
  60. $w .= int_to_words(floor($x/1000000)) .' million';
  61. $r = fmod($x, 1000000);
  62. if($r > 0)
  63. {
  64. $w .= ' ';
  65. if($r < 100)
  66. {
  67. $word .= 'and ';
  68. }
  69. $w .= int_to_words($r);
  70. }
  71. }
  72. }
  73. return $w;
  74. }
  75. if(isset($_POST['num'])){
  76. $word = int_to_words($_POST['num']);
  77. echo $word.'<br /><a href="'.$_SERVER['PHP_SELF'].'"> try again</a><br />';
  78. }else{
  79. echo '
  80. <form method="post" action="'.$_SERVER['PHP_SELF'].'">
  81. <input type="text" name="num">
  82. <input type="submit" value="Convert">
  83. </form>';
  84. }
  85. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: lasavior on August 5, 2011

Actually if you use a loop you could easily expand it to any degree of places vs hard coding every single possibility.

You need to login to post a comment.