This following code for ' Convert Integer Number to Alphabet String in PHP '...
Example:
<?php
function number_to_word_letter($num) {
$and = ' and ';
$comma = ', ';
$minus = '(minus) ';
$point = ' point ';
$box = 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',
20 => 'Twenty',
30 => 'Thirty',
40 => 'Fourty',
50 => 'Fifty',
60 => 'Sixty',
70 => 'Seventy',
80 => 'Eighty',
90 => 'Ninety',
100 => 'Hundred',
1000 => 'Thousand',
1000000 => 'Million',
1000000000 => 'Billion',
1000000000000 => 'Trillion',
1000000000000000 => 'Quadrillion',
1000000000000000000 => 'Quintillion'
);
if (!is_numeric($num)) {
return false;
}
if ($num < 0) {
return $minus . number_to_word_letter(abs($num));
}
$word = $fraction = null;
if (strpos($num, '.') !== false) {
list($num, $fraction) = explode('.', $num);
}
switch (true) {
case $num < 21:
$word = $box[$num];
break;
case $num < 100:
$tens = ((int) ($num / 10)) * 10;
$units = $num % 10;
$word = $box[$tens];
if ($units) {
$word .= ' '. $box[$units];
}
break;
case $num < 1000:
$hundreds = $num / 100;
$remainder = $num % 100;
$word = $box[$hundreds] . ' ' . $box[100];
if ($remainder) {
$word .= $and . number_to_word_letter($remainder);
}
break;
default:
$baseUnit = pow(1000, floor(log($num, 1000)));
$numBaseUnits = (int) ($num / $baseUnit);
$remainder = $num % $baseUnit;
$word = number_to_word_letter($numBaseUnits) . ' ' . $box[$baseUnit];
if ($remainder) {
$word .= $remainder < 100 ? $and : $comma;
$word .= number_to_word_letter($remainder);
}
break;
}
if (null !== $fraction && is_numeric($fraction)) {
$word .= $point;
$words = array();
foreach (str_split((string) $fraction) as $num) {
$words[] = $box[$num];
}
$word .= implode(' ', $words);
}
return $word;
}
?>
Example:
echo number_to_word_letter(0); // Zero
echo number_to_word_letter(10); // Ten
echo number_to_word_letter(100); // Hundred
echo number_to_word_letter(1000); // Thousand
echo number_to_word_letter(123); // One Hundred and Twenty Three
echo number_to_word_letter(-3212); // (minus) Three Thousand, Two Hundred and Twelve
echo number_to_word_letter(-234.5); // (minus) Two Hundred and Thirty Four point Five
No comments:
Post a Comment