Amount to Words
by Hifni Nazeer
HTML
<input type="text" id="inAmount" value=0 />
<div id="divAmountInWord">
Hello
</div>
<button id="btnConvert">
Convert
</button>
JavaScript
$(document).ready(function () {
$("button").click(function () {
var inTxtAmount = $("#inAmount").val()
let amountToWords = moneyToEng(inTxtAmount);
$("#divAmountInWord").text(amountToWords)
})
})
/*
Source: https://stackoverflow.com/questions/67477587/dynamically-convert-dollar-amount-to-text-to-include-the-words-rupees-and-ce
These arrays are indexed to the number that each element represents
*/
const ones = [
"",
"one ",
"two ",
"three ",
"four ",
"five ",
"six ",
"seven ",
"eight ",
"nine ",
]
const teen = [
"ten ",
"eleven ",
"twelve ",
"thirteen ",
"fourteen ",
"fifteen ",
"sixteen ",
"seventeen ",
"eighteen ",
"nineteen ",
]
const tens = [
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety",
]
const high = ["hundred ", "thousand ", "million ", "billion "]
// Helper function - a simple logger
const log = (data) => console.log(data)
/*
This function takes 2 numbers and matches the first parameter to the index of the
tens or teen array. The second parameter matches to the index of the ones array.
A word number between 1 and 99 is returned.
*/
const tensOnes = (t, o) =>
+t == 0
? ones[+o]
: +t == 1
? teen[+o]
: +t > 1 && +o == 0
? tens[+t - 2]
: tens[+t - 2] + "-" + ones[+o]
// function takes a number and returns a string number with 2 decimals
const fltN = (float) => [...parseFloat(float).toFixed(2)]
/*
This function takes an array created by moneyToEng() function and returns a word
version of the given number. A switch() with 10 cases (9,999,999,999 is max) is
used to call tensOnes() function. Before the string is returned, there are a few
fixes to make it grammatically correct.
*/
const stepper = (array) => {
const D = array[0]
const C = array[1]
let size = D.length
let word
switch (size) {
case 0:
word = C
break
case 1:
word = tensOnes(0, D[0]) + "rupees " + C
break
case...