function convertAmountToWords(amount) {
const words = [
"Zero",
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten",
"Eleven",
"Twelve",
"Thirteen",
"Fourteen",
"Fifteen",
"Sixteen",
"Seventeen",
"Eighteen",
"Nineteen",
];
const tensWords = [
"",
"",
"Twenty",
"Thirty",
"Forty",
"Fifty",
"Sixty",
"Seventy",
"Eighty",
"Ninety",
];
const centsWords = [
"",
"One Cent",
"Two Cents",
"Three Cents",
"Four Cents",
"Five Cents",
"Six Cents",
"Seven Cents",
"Eight Cents",
"Nine Cents",
];
const [dollars, cents] = amount.slice(1).split(".");
const dollarWords =
dollars === "0" ?
"Zero" :
dollars < 20 ?
words[Number(dollars)] :
tensWords[Math.floor(dollars / 10)] +
(dollars % 10 === 0 ? "" : ` ${words[dollars % 10]}`);
const centWords = cents ? centsWords[Number(cents)] : "";
return `${dollarWords} Dollar and ${centWords}`;
}
const amountInWords = convertAmountToWords("$10.20");
console.log(amountInWords); // Output: "Ten Dollar and Twenty Cents"
In this code example that (.20) is undefined, I want to above example is ($10.20),
I want "Ten Dollar and Twenty Cents".
How to recode above example.
Help me please.
2
Answers
I fixed the logic for handling the cents. By using the tensWords and words arrays, I converted the cents into words. The code checks if cents exist and are not zero before including the cents part in the final result. This ensures that both the dollar and cent parts are correctly converted and displayed in the desired format.
It’s because your
centsWords
array only goes up to nine. So instead of creating a new array, it’s easier and better to use the same array and the same method you used to generate thedollarWords
.