Created
June 29, 2024 06:25
-
-
Save sanjaybhowmick/c5e6af46f9a4b123da7bf50dd4d768c0 to your computer and use it in GitHub Desktop.
Indian currency numeric to words conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function convertToIndianCurrencyWords($number) { | |
$ones = array( | |
0 => '', 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four', | |
5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine' | |
); | |
$teens = array( | |
11 => 'Eleven', 12 => 'Twelve', 13 => 'Thirteen', 14 => 'Fourteen', | |
15 => 'Fifteen', 16 => 'Sixteen', 17 => 'Seventeen', 18 => 'Eighteen', | |
19 => 'Nineteen' | |
); | |
$tens = array( | |
1 => 'Ten', 2 => 'Twenty', 3 => 'Thirty', 4 => 'Forty', 5 => 'Fifty', | |
6 => 'Sixty', 7 => 'Seventy', 8 => 'Eighty', 9 => 'Ninety' | |
); | |
$hundreds = array( | |
'', 'Hundred', 'Thousand', 'Lakh', 'Crore' | |
); | |
$words = array(); | |
if ($number < 0) { | |
$words[] = 'Minus'; | |
$number = abs($number); | |
} | |
$numString = (string)$number; | |
$numDigits = strlen($numString); | |
$numChunks = ceil($numDigits / 2); | |
$numChunkLen = $numDigits % 2 ?: 2; | |
$numChunkPos = 0; | |
for ($i = 0; $i < $numChunks; ++$i) { | |
$numChunk = substr($numString, $numChunkPos, $numChunkLen); | |
$numChunk = (int)$numChunk; | |
if ($numChunk != 0) { | |
$numChunkWords = array(); | |
if ($numChunk >= 10 && $numChunk <= 19) { | |
$numChunkWords[] = $teens[$numChunk]; | |
} elseif ($numChunk >= 20) { | |
$tensDigit = (int)($numChunk / 10); | |
$numChunkWords[] = $tens[$tensDigit]; | |
$onesDigit = $numChunk % 10; | |
if ($onesDigit != 0) { | |
$numChunkWords[] = $ones[$onesDigit]; | |
} | |
} elseif ($numChunk != 0) { | |
$numChunkWords[] = $ones[$numChunk]; | |
} | |
if (!empty($numChunkWords)) { | |
$words = array_merge($words, $numChunkWords); | |
if ($numChunkPos > 0) { | |
$words[] = $hundreds[$i]; | |
} | |
} | |
} | |
$numChunkPos += $numChunkLen; | |
$numChunkLen = 2; | |
} | |
return implode(' ', $words); | |
} | |
$number = 123456789; // Example number | |
$words = convertToIndianCurrencyWords($number); | |
echo ucfirst($words) . ' Rupees Only'; // Output: Twelve Crore Thirty Four Lakh Fifty Six Thousand Seven Hundred Eighty Nine Rupees Only | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment