Converting Digits to Words using PHP
Details
Have you ever wondered how you can convert a numerical digit into its corresponding word representation? Maybe you need to display numbers in a more human-readable format or create a dynamic invoice generator. In this tutorial, we'll explore how to achieve this using PHP.
The Problem
Consider a scenario where you have a number, let's say 5, and you want to convert it into the word representation, which in this case would be "five". This might seem like a trivial task, but having a clear and concise method to accomplish this can greatly improve the readability and maintainability of your code.
The Solution
We can solve this problem by creating a simple mapping between digits and their word equivalents. Let's see how we can implement this in PHP:
$number = 5025.25; $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) ? 's' : 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) ? "." . $words[$point / 10] . " " . $words[$point = $point % 10] : ''; echo $result . "Rupees " . $points . " Paise";