Robson » Little Red Book » Sum of money in words

Chapter 6 - Question 9

Given as input a number of pounds (less than 1000) and a number of pence (less than 100), output the equivalent sum in words, as on a cheque.

Solution 1

This PHP script uses my Number To Words function:

<?
   function number_to_words($n)
   {
       $number = array(
           'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
           'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
           'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
           );
           
       $tens = array(
           'zero', 'ten', 'twenty', 'thirty', 'forty', 'fifty',
           'sixty', 'seventy', 'eighty', 'ninety'
       );
 
       if (!$n)
           $output = 'zero';
       else if ($n == 1000)
           $output = 'one thousand';
       else
       {
           if ($n > 99 && $n < 1000)
           {
               $output = $number[intval($n/100)] . ' hundred';
               $n %= 100;
               if ($n)
                   $output .= ' and ';
           }
           if ($n >= 1 && $n <= 19)
               $output .= $number[$n];
           else if ($n)
           {
               $output .= $tens[intval($n/10)];
               if ($n % 10)
                   $output .= ' ' . $number[$n % 10];
           }
       }
       return $output;
   }
   
   // make up some values
   $pounds = mt_rand(1, 1000);
   $pence = mt_rand(1, 100);
   
   // show the amount in currency format
   echo sprintf(, $pounds, $pence);
   // show the amount in words
   echo '<br />' . ucfirst(number_to_words($pounds)) . ' pounds and ' . number_to_words($pence) . ' pence';
?>

Which produces:

119.60
One hundred and nineteen pounds and sixty pence

Log

© 2004-14 robson | cc unless stated