Monday, 18 July 2011

Display english words for numbers between 1 and 999

Program to display the english words for a number between 1-999.

The words for numbers between 1-19 should be stored in an array as they are unique. This is also applicable to multiples of ten when
the number is less than 100.

1. Check if the number is 3 digit or 2 digit. If it is 3, store the third digit.
2. Call the function for displaying the last two digits
3. If the number is 2 digit, just call the function

The function
The last two digits and the array are passed to the function
Check if the two digits are less than 21 or a multiple of 10. If it is, just output the corresponding value stored in the array.
Else, find the 100th's place digit. Return the corresponding values for the 100th's place and the 10th's place.

<?php
//Return the english words for the last two digits of the number
function two_digit($last_two_digits,$array)
 {
      $last_digit=fmod($last_two_digits,10); //Find the digit in the 10th's place i.e, the final digit
      if($last_two_digits<21 || $last_digit==0 ) //Check if the last two digits is less than 21. If it is, then just return the value in the array
   {
       return $array[$last_two_digits];
   }
   else
   {
       $mul_ten= $last_two_digits-$last_digit; // Find the 100th's place.For eg: 94 gives 94-4=90.
       return $array[$mul_ten]."-".$array[$last_digit];
   }
 }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">

</style>
</head>
<body>
    <form method="post">
      <input type="text" name="number"/>
      <input type="submit" name="submit" value="Convert"/>
    </form>
 <?php

  $array = array(1=>"One",2=>"Two",3=>"Three",4=>"Four",5=>"Five",6=>"Six",7=>"Seven",8=>"Eight",9=>"Nine",10=>"Ten",11=>"Eleven",
                 12=>"Twelve",13=>"Thirteen",14=>"Fourteen",15=>"Fifteen",16=>"Sixteen",17=>"Seventeen",18=>"Eighteen",19=>"Nineteen",
                 20=>"Twenty",30=>"Thirty",40=>"Forty",50=>"Fifty",60=>"Sixty",70=>"Seventy",80=>"Eighty",90=>"Ninety",
                 100=>"Hundred");
 if(isset($_POST['submit']))
 {
   $key=$_POST['number'];//The value entered by the user is stored in the variable, $key
   if($key<1000 && $key>0) 
  {
     $digit_three=floor($key/100); //Find the 1000th place digit

     if($digit_three>=1)//if the number is greater than 99
        { 
          $remainder_hundred=fmod($key,100);//Find the last two digits
          $last_two_digits=two_digit($remainder_hundred,$array);//function call. Returns the english words for the last two digits
          echo $array[$digit_three]." Hundred  ".$last_two_digits;     
         }
      else//if number is less than 100
        {
          $two_digit=two_digit($key,$array);
          echo $two_digit;
        }
   }
 else
 {
   echo "Please enter a number between 1-999";   
  }
}
?>

No comments:

Post a Comment