I am making a code which converts the given amount into words, heres is what I have got after googling. But I think its a little lengthy code to achieve a simple task. Two R
Though, this question has been answered - still I want to share something I recently developed in java script (based on the logic of an old C#. Net implementation I found in Internet) for converting Indian currency values to Words. It can handle up to 40 digits. You can have a look.
Usage: InrToWordConverter.Initialize();. var inWords = InrToWordConverter.ConvertToWord(amount);
Implementation:
htPunctuation = {};
listStaticSuffix = {};
listStaticPrefix = {};
listHelpNotation = {};
var InrToWordConverter = function () {
};
InrToWordConverter.Initialize = function () {
InrToWordConverter.LoadStaticPrefix();
InrToWordConverter.LoadStaticSuffix();
InrToWordConverter.LoadHelpofNotation();
};
InrToWordConverter.ConvertToWord = function (value) {
value = value.toString();
if (value) {
var tokens = value.split(".");
var rsPart = "";
var psPart = "";
if (tokens.length === 2) {
rsPart = String.trim(tokens[0]) || "0";
psPart = String.trim(tokens[1]) || "0";
}
else if (tokens.length === 1) {
rsPart = String.trim(tokens[0]) || "0";
psPart = "0";
}
else {
rsPart = "0";
psPart = "0";
}
htPunctuation = {};
var rsInWords = InrToWordConverter.ConvertToWordInternal(rsPart) || "Zero";
var psInWords = InrToWordConverter.ConvertToWordInternal(psPart) || "Zero";
var result = "Rupees " + rsInWords + "and " + psInWords + " Paise.";
return result;
}
};
InrToWordConverter.ConvertToWordInternal = function (value) {
var convertedString = "";
if (!(value.toString().length > 40))
{
if (InrToWordConverter.IsNumeric(value.toString()))
{
try
{
var strValue = InrToWordConverter.Reverse(value);
switch (strValue.length)
{
case 1:
if (parseInt(strValue.toString()) > 0) {
convertedString = InrToWordConverter.GetWordConversion(value);
}
else {
convertedString = "Zero ";
}
break;
case 2:
convertedString = InrToWordConverter.GetWordConversion(value);
break;
default:
InrToWordConverter.InsertToPunctuationTable(strValue);
InrToWordConverter.ReverseHashTable();
convertedString = InrToWordConverter.ReturnHashtableValue();
break;
}
}
catch (exception) {
convertedString = "Unexpected Error Occured <br/>";
}
}
else {
convertedString = "Please Enter Numbers Only, Decimal Values Are not supported";
}
}
else {
convertedString = "Please Enter Value in Less Then or Equal to 40 Digit";
}
return convertedString;
};
InrToWordConverter.IsNumeric = function (valueInNumeric) {
var isFine = true;
valueInNumeric = valueInNumeric || "";
var len = valueInNumeric.length;
for (var i = 0; i < len; i++) {
var ch = valueInNumeric[i];
if (!(ch >= '0' && ch <= '9')) {
isFine = false;
break;
}
}
return isFine;
};
InrToWordConverter.ReturnHashtableValue = function () {
var strFinalString = "";
var keysArr = [];
for (var key in htPunctuation) {
keysArr.push(key);
}
for (var i = keysArr.length - 1; i >= 0; i--) {
var hKey = keysArr[i];
if (InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) !== "") {
strFinalString = strFinalString + InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) + InrToWordConverter.StaticPrefixFind((hKey).toString());
}
}
return strFinalString;
};
InrToWordConverter.ReverseHashTable = function () {
var htTemp = {};
for (var key in htPunctuation) {
var item = htPunctuation[key];
htTemp[key] = InrToWordConverter.Reverse(item.toString());
}
htPunctuation = {};
htPunctuation = htTemp;
};
InrToWordConverter.InsertToPunctuationTable = function (strValue) {
htPunctuation[1] = strValue.substr(0, 3).toString();
var j = 2;
for (var i = 3; i < strValue.length; i = i + 2) {
if (strValue.substr(i).length > 0) {
if (strValue.substr(i).length >= 2) {
htPunctuation[j] = strValue.substr(i, 2).toString();
}
else {
htPunctuation[j] = strValue.substr(i, 1).toString();
}
}
else {
break;
}
j++;
}
};
InrToWordConverter.Reverse = function (strValue) {
var reversed = "";
for (var i in strValue) {
var ch = strValue[i];
reversed = ch + reversed;
}
return reversed;
};
InrToWordConverter.GetWordConversion = function (inputNumber) {
var toReturnWord = "";
if (inputNumber.length <= 3 && inputNumber.length > 0) {
if (inputNumber.length === 3) {
if (parseInt(inputNumber.substr(0, 1)) > 0) {
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1)) + "Hundred ";
}
var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 2));
if (tempString === "")
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1) + "0");
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(2, 1));
}
toReturnWord = toReturnWord + tempString;
}
if (inputNumber.length === 2)
{
var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 2));
if (tempString === "")
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1) + "0");
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1));
}
toReturnWord = toReturnWord + tempString;
}
if (inputNumber.length === 1)
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1));
}
}
return toReturnWord;
};
InrToWordConverter.StaticSuffixFind = function (numberKey) {
var valueFromNumber = "";
for (var key in listStaticSuffix) {
if (String.trim(key.toString()) === String.trim(numberKey)) {
valueFromNumber = listStaticSuffix[key].toString();
break;
}
}
return valueFromNumber;
};
InrToWordConverter.StaticPrefixFind = function (numberKey) {
var valueFromNumber = "";
for (var key in listStaticPrefix) {
if (String.trim(key) === String.trim(numberKey)) {
valueFromNumber = listStaticPrefix[key].toString();
break;
}
}
return valueFromNumber;
};
InrToWordConverter.StaticHelpNotationFind = function (numberKey) {
var helpText = "";
for (var key in listHelpNotation) {
if (String.trim(key.toString()) === String.trim(numberKey)) {
helpText = listHelpNotation[key].toString();
break;
}
}
return helpText;
};
InrToWordConverter.LoadStaticPrefix = function () {
listStaticPrefix[2] = "Thousand ";
listStaticPrefix[3] = "Lac ";
listStaticPrefix[4] = "Crore ";
listStaticPrefix[5] = "Arab ";
listStaticPrefix[6] = "Kharab ";
listStaticPrefix[7] = "Neel ";
listStaticPrefix[8] = "Padma ";
listStaticPrefix[9] = "Shankh ";
listStaticPrefix[10] = "Maha-shankh ";
listStaticPrefix[11] = "Ank ";
listStaticPrefix[12] = "Jald ";
listStaticPrefix[13] = "Madh ";
listStaticPrefix[14] = "Paraardha ";
listStaticPrefix[15] = "Ant ";
listStaticPrefix[16] = "Maha-ant ";
listStaticPrefix[17] = "Shisht ";
listStaticPrefix[18] = "Singhar ";
listStaticPrefix[19] = "Maha-singhar ";
listStaticPrefix[20] = "Adant-singhar ";
};
InrToWordConverter.LoadStaticSuffix = function () {
listStaticSuffix[1] = "One ";
listStaticSuffix[2] = "Two ";
listStaticSuffix[3] = "Three ";
listStaticSuffix[4] = "Four ";
listStaticSuffix[5] = "Five ";
listStaticSuffix[6] = "Six ";
listStaticSuffix[7] = "Seven ";
listStaticSuffix[8] = "Eight ";
listStaticSuffix[9] = "Nine ";
listStaticSuffix[10] = "Ten ";
listStaticSuffix[11] = "Eleven ";
listStaticSuffix[12] = "Twelve ";
listStaticSuffix[13] = "Thirteen ";
listStaticSuffix[14] = "Fourteen ";
listStaticSuffix[15] = "Fifteen ";
listStaticSuffix[16] = "Sixteen ";
listStaticSuffix[17] = "Seventeen ";
listStaticSuffix[18] = "Eighteen ";
listStaticSuffix[19] = "Nineteen ";
listStaticSuffix[20] = "Twenty ";
listStaticSuffix[30] = "Thirty ";
listStaticSuffix[40] = "Fourty ";
listStaticSuffix[50] = "Fifty ";
listStaticSuffix[60] = "Sixty ";
listStaticSuffix[70] = "Seventy ";
listStaticSuffix[80] = "Eighty ";
listStaticSuffix[90] = "Ninty ";
};
InrToWordConverter.LoadHelpofNotation = function () {
listHelpNotation[2] = "=1,000 (3 Trailing Zeros)";
listHelpNotation[3] = "=1,00,000 (5 Trailing Zeros)";
listHelpNotation[4] = "=1,00,00,000 (7 Trailing Zeros)";
listHelpNotation[5] = "=1,00,00,00,000 (9 Trailing Zeros)";
listHelpNotation[6] = "=1,00,00,00,00,000 (11 Trailing Zeros)";
listHelpNotation[7] = "=1,00,00,00,00,00,000 (13 Trailing Zeros)";
listHelpNotation[8] = "=1,00,00,00,00,00,00,000 (15 Trailing Zeros)";
listHelpNotation[9] = "=1,00,00,00,00,00,00,00,000 (17 Trailing Zeros)";
listHelpNotation[10] = "=1,00,00,00,00,00,00,00,00,000 (19 Trailing Zeros)";
listHelpNotation[11] = "=1,00,00,00,00,00,00,00,00,00,000 (21 Trailing Zeros)";
listHelpNotation[12] = "=1,00,00,00,00,00,00,00,00,00,00,000 (23 Trailing Zeros)";
listHelpNotation[13] = "=1,00,00,00,00,00,00,00,00,00,00,00,000 (25 Trailing Zeros)";
listHelpNotation[14] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,000 (27 Trailing Zeros)";
listHelpNotation[15] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (29 Trailing Zeros)";
listHelpNotation[16] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (31 Trailing Zeros)";
listHelpNotation[17] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (33 Trailing Zeros)";
listHelpNotation[18] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (35 Trailing Zeros)";
listHelpNotation[19] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (37 Trailing Zeros)";
listHelpNotation[20] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (39 Trailing Zeros)";
};
if (!String.trim) {
String.trim = function (str) {
var result = "";
var firstNonWhiteSpaceFound = false;
var startIndex = -1;
var endIndex = -1;
if (str) {
for (var i = 0; i < str.length; i++) {
if (firstNonWhiteSpaceFound === false) {
if (str[i] === ' ' || str[i] === '\t') {
continue;
}
else {
firstNonWhiteSpaceFound = true;
startIndex = i;
endIndex = i;
}
}
else {
if (str[i] === ' ' || str[i] === '\t') {
continue;
}
else {
endIndex = i;
}
}
}
if (startIndex !== -1 && endIndex !== -1) {
result = str.slice(startIndex, endIndex + 1);
}
}
return result;
};
}
Try this code with a Turkish currency compliant JavaScript
function dene() {
var inpt = document.getElementById("tar1").value;
var spt = inpt.split('');
spt.reverse();
var tek = ["", "Bir", "İki", "Üç", "Dört", "Beş", "Altı", "Yedi", "Sekiz", "Dokuz"];
var onlu = ["", "On", "Yirmi", "Otuz", "Kırk", "Elli", "Atmış", "Yetmiş", "Seksen", "Doksan"];
var Yuz = ["", "Yüz", "İkiYüz", "Üçyüz", "DörtYüz", "BeşYüz", "AltıYüz", "YediYüz", "SekizYüz", "DokuzYüz"];
var ska = ["", "", "", "", "Bin", "Milyon", "Milyar", "Trilyon", "Katrilyon", "Kentilyon"];
var i, j;
var bas3 = "";
var bas6 = "";
var bas9 = "";
var bas12 = "";
var total;
for(i = 0; i < 1; i++) {
bas3 += Yuz[spt[i+2]] + onlu[spt[i+1]] + tek[spt[i]];
bas6 += Yuz[spt[i+5]] + onlu[spt[i+4]] + tek[spt[i+3]] + ska[4];
bas9 += Yuz[spt[i+8]] + onlu[spt[i+7]] + tek[spt[i+6]] + ska[5];
bas12 += Yuz[spt[i+11]] + onlu[spt[i+10]] + tek[spt[i+9]] + ska[6];
if(inpt.length < 4) {
bas6 = '';
bas9 = '';
}
if(inpt.length > 6 && inpt.slice(5, 6) == 0) {
bas6 = bas6.replace(/Bin/g, '');
}
if(inpt.length < 7) {
bas9 = '';
}
if(inpt.length > 9 && inpt.slice(1,3) == 000){
bas9 = bas9.replace(/Milyon/g, '');
}
if(inpt.length < 10) {
bas12 = '';
}
}
total = bas12 + bas9 + bas6 + bas3;
total = total.replace(NaN, '');
total = total.replace(undefined, '');
document.getElementById('demo').innerHTML =
total;
}
If you need with Cent then you may use this one
<script>
var iWords = ['zero', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine'];
var ePlace = ['ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen'];
var tensPlace = ['', ' ten', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety'];
var inWords = [];
var numReversed, inWords, actnumber, i, j;
function tensComplication() {
if (actnumber[i] == 0) {
inWords[j] = '';
} else if (actnumber[i] == 1) {
inWords[j] = ePlace[actnumber[i - 1]];
} else {
inWords[j] = tensPlace[actnumber[i]];
}
}
function convertAmount() {
var numericValue = document.getElementById('bdt').value;
numericValue = parseFloat(numericValue).toFixed(2);
var amount = numericValue.toString().split('.');
var taka = amount[0];
var paisa = amount[1];
document.getElementById('container').innerHTML = convert(taka) +" taka and "+ convert(paisa)+" paisa only";
}
function convert(numericValue) {
inWords = []
if(numericValue == "00" || numericValue =="0"){
return 'zero';
}
var obStr = numericValue.toString();
numReversed = obStr.split('');
actnumber = numReversed.reverse();
if (Number(numericValue) == 0) {
document.getElementById('container').innerHTML = 'BDT Zero';
return false;
}
var iWordsLength = numReversed.length;
var finalWord = '';
j = 0;
for (i = 0; i < iWordsLength; i++) {
switch (i) {
case 0:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
inWords[j] = inWords[j] + '';
break;
case 1:
tensComplication();
break;
case 2:
if (actnumber[i] == '0') {
inWords[j] = '';
} else if (actnumber[i - 1] !== '0' && actnumber[i - 2] !== '0') {
inWords[j] = iWords[actnumber[i]] + ' hundred';
} else {
inWords[j] = iWords[actnumber[i]] + ' hundred';
}
break;
case 3:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
if (actnumber[i + 1] !== '0' || actnumber[i] > '0') {
inWords[j] = inWords[j] + ' thousand';
}
break;
case 4:
tensComplication();
break;
case 5:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
if (actnumber[i + 1] !== '0' || actnumber[i] > '0') {
inWords[j] = inWords[j] + ' lakh';
}
break;
case 6:
tensComplication();
break;
case 7:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
inWords[j] = inWords[j] + ' crore';
break;
case 8:
tensComplication();
break;
default:
break;
}
j++;
}
inWords.reverse();
for (i = 0; i < inWords.length; i++) {
finalWord += inWords[i];
}
return finalWord;
}
</script>
<input type="text" name="bdt" id="bdt" />
<input type="button" name="sr1" value="Click Here" onClick="convertAmount()"/>
<div id="container"></div>
js fiddle
Here taka mean USD and paisa mean cent
You can check my version from github. It is not so hard way. I test this for the numbers between 0 and 9999, but you can extend array if you would like digits to words
I have created customized function ntsConvert()
to convert number to words
function ntsConvert(value) {
let input = String(value).split('');
let mapData = {
"0": "Zero",
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine"
};
let output = '';
var tempArray = []
for (let i = 0; i < input.length; i++) {
tempArray.push(mapData[input[i]])
}
output = tempArray.join(' ');
return output;
}
console.log(ntsConvert(12345)) // 'One Two Three Four Five'
Converting the input string into a number rather than keeping it as a string, limits the solution to the maximum allowed float / integer value on that machine/browser. My script below handles currency up to 1 Trillion dollars - 1 cent :-). I can be extended to handle up to 999 Trillions by adding 3 or 4 lines of code.
var ones = ["","One","Two","Three","Four","Five","Six","Seven","Eight",
"Nine","Ten","Eleven","Twelve","Thirteen","Fourteen",
"Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"];
var tens = ["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy",
"Eighty","Ninety"];
function words999(n999) { // n999 is an integer less than or equal to 999.
//
// Accept any 3 digit int incl 000 & 999 and return words.
//
var words = ''; var Hn = 0; var n99 = 0;
Hn = Math.floor(n999 / 100); // # of hundreds in it
if (Hn > 0) { // if at least one 100
words = words99(Hn) + " Hundred"; // one call for hundreds
}
n99 = n999 - (Hn * 100); // subtract the hundreds.
words += ((words == '')?'':' ') + words99(n99); // combine the hundreds with tens & ones.
return words;
} // function words999( n999 )
function words99(n99) { // n99 is an integer less than or equal to 99.
//
// Accept any 2 digit int incl 00 & 99 and return words.
//
var words = ''; var Dn = 0; var Un = 0;
Dn = Math.floor(n99 / 10); // # of tens
Un = n99 % 10; // units
if (Dn > 0 || Un > 0) {
if (Dn < 2) {
words += ones[Dn * 10 + Un]; // words for a # < 20
} else {
words += tens[Dn];
if (Un > 0) words += "-" + ones[Un];
}
} // if ( Dn > 0 || Un > 0 )
return words;
} // function words99( n99 )
function getAmtInWords(id1, id2) { // use numeric value of id1 to populate text in id2
//
// Read numeric amount field and convert into word amount
//
var t1 = document.getElementById(id1).value;
var t2 = t1.trim();
amtStr = t2.replace(/,/g,''); // $123,456,789.12 = 123456789.12
dotPos = amtStr.indexOf('.'); // position of dot before cents, -ve if it doesn't exist.
if (dotPos > 0) {
dollars = amtStr.slice(0,dotPos); // 1234.56 = 1234
cents = amtStr.slice(dotPos+1); // 1234.56 = .56
} else if (dotPos == 0) {
dollars = '0';
cents = amtStr.slice(dotPos+1); // 1234.56 = .56
} else {
dollars = amtStr.slice(0); // 1234 = 1234
cents = '0';
}
t1 = '000000000000' + dollars; // to extend to trillion, use 15 zeros
dollars = t1.slice(-12); // and -15 here.
billions = Number(dollars.substr(0,3));
millions = Number(dollars.substr(3,3));
thousands = Number(dollars.substr(6,3));
hundreds = Number(dollars.substr(9,3));
t1 = words999(billions); bW = t1.trim(); // Billions in words
t1 = words999(millions); mW = t1.trim(); // Millions in words
t1 = words999(thousands); tW = t1.trim(); // Thousands in words
t1 = words999(hundreds); hW = t1.trim(); // Hundreds in words
t1 = words99(cents); cW = t1.trim(); // Cents in words
var totAmt = '';
if (bW != '') totAmt += ((totAmt != '') ? ' ' : '') + bW + ' Billion';
if (mW != '') totAmt += ((totAmt != '') ? ' ' : '') + mW + ' Million';
if (tW != '') totAmt += ((totAmt != '') ? ' ' : '') + tW + ' Thousand';
if (hW != '') totAmt += ((totAmt != '') ? ' ' : '') + hW + ' Dollars';
if (cW != '') totAmt += ((totAmt != '') ? ' and ' : '') + cW + ' Cents';
// alert('totAmt = ' + totAmt); // display words in a alert
t1 = document.getElementById(id2).value;
t2 = t1.trim();
if (t2 == '') document.getElementById(id2).value = totAmt;
return false;
} // function getAmtInWords( id1, id2 )
// ======================== [ End Code ] ====================================