Convert Numbers to Words in PHP


Convert Numbers to Words in PHP

In this tutorial, we will not discuss step-by-step how to convert numbers to words in PHP. This feature is very important and plays a vital role in displaying the invoice amounts in the custom application software, billing software, etc. In this example, multiple functions have been used to display the converted result. Below I will put a PHP file by which you can calculate the result.

Let us take a number. For eg:- 325 and put in the below code

Also read, How to display PDF file in PHP on browser

numbertoword.php:-

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php
    $number = number_format((float)(325),2,'.','');
   $no = floor($number);
   $point = round($number - $no, 2) * 100;
   $hundred = null;
   $digits_1 = strlen($no);
   $i = 0;
   $str = array();
   $words = array('0' => '', '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');
   $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
   while ($i < $digits_1) {
     $divider = ($i == 2) ? 10 : 100;
     $number = floor($no % $divider);
     $no = floor($no / $divider);
     $i += ($divider == 10) ? 1 : 2;
     if ($number) {
        $plural = (($counter = count($str)) && $number > 9) ? '' : null;
        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
        $str [] = ($number < 21) ? $words[$number] .
            " " . $digits[$counter] . $plural . " " . $hundred
            :
            $words[floor($number / 10) * 10]
            . " " . $words[$number % 10] . " "
            . $digits[$counter] . $plural . " " . $hundred;
     } else $str[] = null;
  }
  $str = array_reverse($str);
  $result = implode('', $str);
  $points = ($point) ?
    "Point " . $words[$point / 10] . " " . 
          $words[$point = $point % 10] : '';
  $amountinwords = 'Rupees'.'&nbsp;&nbsp;'.ucwords($result).'Only';
  echo $amountinwords;
 ?>
</body>
</html>

In the above code, all the words related to digits ranging from 1 to 100 and so on are stored separately in the different arrays to be used inside the while loop.

After executing the above code, the output will be

Rupees  Three Hundred And Twenty Five Only

Conclusion:- I hope this tutorial will help you to convert numbers to words in PHP. If there is any doubt then please leave a comment below.


Leave a Comment