Convert Number to Words in PHP
Convert Number to Words in PHP
Introduction
Sometimes, web applications need to convert numbers into words. This is commonly used in invoice systems, billing software, cheque printing, payroll applications, and financial reports.
For example:
1250becomes
One Thousand Two Hundred FiftyIn this tutorial, you'll learn how to convert numbers to words in PHP using a reusable function with complete source code and examples.
Why Convert Numbers to Words?
Converting numbers into words is useful for:
- Invoice generation
- Cheque printing
- Salary slips
- Banking applications
- Billing software
- Financial reports
<?php
function numberToWords($num)
{
$ones = array(
0 => "zero",
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"
);
$tens = array(
2 => "twenty",
3 => "thirty",
4 => "forty",
5 => "fifty",
6 => "sixty",
7 => "seventy",
8 => "eighty",
9 => "ninety"
);
if ($num < 20) {
return $ones[$num];
} elseif ($num < 100) {
return $tens[floor($num / 10)] . ($num % 10 != 0 ? " " . $ones[$num % 10] : "");
} else {
return "";
}
}
function decimalToWords($decimal)
{
$decimalStr = str_pad($decimal, 2, "0", STR_PAD_RIGHT); // Ensure it has 2 digits
$decimalWords = "";
for ($i = 0; $i < strlen($decimalStr); $i++) {
$digit = intval($decimalStr[$i]);
$decimalWords .= numberToWords($digit) . " ";
}
return trim($decimalWords);
}
function convertNumberToWords($number)
{
$formattedNumber = number_format($number, 2, '.', '');
$parts = explode(".", $formattedNumber);
$integerPart = isset($parts[0]) ? intval($parts[0]) : 0;
$decimalPart = isset($parts[1]) ? intval($parts[1]) : 0;
$integerWords = numberToWords($integerPart);
$decimalWords = decimalToWords($decimalPart);
return ucwords($integerWords) . " and " . ucwords($decimalWords);
}
$number = 45.88;
echo convertNumberToWords($number);
Comments
Post a Comment