Converting Numbers to Words in JavaScript: A Step-by-Step Guide
When developing web applications, especially financial ones, you might need to convert numbers to words. This is useful for creating checks, invoices, and various financial reports. In this article, we’ll walk you through creating a JavaScript function that converts numbers to words, supporting both whole numbers and decimals.
Example: 1234569.52 is One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Nine and Fifty Two Cents
Read Numbers to Words Online
Number to Words Converter
Why Convert Numbers to Words?
- Check Writing: Ensures that the amount is correctly interpreted.
- Invoices: Adds a professional touch to financial documents.
- Reports: Improves clarity and presentation.
Step-by-Step Instructions
Step 1: Define the Basic Number Words
First, define arrays for basic number words such as units, teens, and tens:
const units = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"];
const teens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
const tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
const thousands = ["", "Thousand", "Million", "Billion"];
Step 2: Create the Conversion Functions
Next, create the main function numberToWords
to handle the conversion and a helper function convertToWords
to handle groups of three digits:
function numberToWords(number) {
if (number === 0) return "Zero";
let words = "";
let numStr = number.toString();
let numArr = numStr.split(".");
let integerPart = parseInt(numArr[0]);
let fractionalPart = numArr.length > 1 ? parseInt(numArr[1]) : 0;
words = convertToWords(integerPart);
if (fractionalPart > 0) {
words += " and " + convertToWords(fractionalPart) + " Cents";
}
return words;
}
function convertToWords(number) {
let word = "";
let numStr = number.toString();
let numLength = numStr.length;
let numGroupCount = Math.ceil(numLength / 3);
let numGroups = [];
for (let i = 0; i < numGroupCount; i++) {
numGroups[i] = parseInt(numStr.slice(Math.max(0, numLength - 3 * (i + 1)), numLength - 3 * i));
}
for (let i = 0; i < numGroups.length; i++) {
if (numGroups[i] !== 0) {
word = convertHundreds(numGroups[i]) + " " + thousands[i] + " " + word;
}
}
return word.trim();
}
function convertHundreds(number) {
let word = "";
if (number >= 100) {
word += units[Math.floor(number / 100)] + " Hundred ";
number = number % 100;
}
if (number >= 10 && number < 20) {
word += teens[number - 10] + " ";
} else {
word += tens[Math.floor(number / 10)] + " ";
word += units[number % 10] + " ";
}
return word.trim();
}
Step 3: Test the Function
Finally, test the function with different numbers to ensure it works correctly:
console.log(numberToWords(123456789.45)); // "One Hundred Twenty-Three Million Four Hundred Fifty-Six Thousand Seven Hundred Eighty-Nine and Forty-Five Cents"
console.log(numberToWords(1001)); // "One Thousand One"
console.log(numberToWords(0)); // "Zero"
HTML and JavaScript Example: Converting Numbers to Words
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number to Words Converter</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
}
input, button {
padding: 10px;
margin: 5px 0;
font-size: 1em;
}
button {
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.result {
margin-top: 20px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h1>Number to Words Converter</h1>
<input type="number" id="numberInput" placeholder="Enter a number">
<button onclick="convertNumberToWords()">Convert</button>
<div class="result" id="result"></div>
</div>
<script>
const units = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"];
const teens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
const tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
const thousands = ["", "Thousand", "Million", "Billion"];
function numberToWords(number) {
if (number === 0) return "Zero";
let words = "";
let numStr = number.toString();
let numArr = numStr.split(".");
let integerPart = parseInt(numArr[0]);
let fractionalPart = numArr.length > 1 ? parseInt(numArr[1]) : 0;
words = convertToWords(integerPart);
if (fractionalPart > 0) {
words += " and " + convertToWords(fractionalPart) + " Cents";
}
return words;
}
function convertToWords(number) {
let word = "";
let numStr = number.toString();
let numLength = numStr.length;
let numGroupCount = Math.ceil(numLength / 3);
let numGroups = [];
for (let i = 0; i < numGroupCount; i++) {
numGroups[i] = parseInt(numStr.slice(Math.max(0, numLength - 3 * (i + 1)), numLength - 3 * i));
}
for (let i = 0; i < numGroups.length; i++) {
if (numGroups[i] !== 0) {
word = convertHundreds(numGroups[i]) + " " + thousands[i] + " " + word;
}
}
return word.trim();
}
function convertHundreds(number) {
let word = "";
if (number >= 100) {
word += units[Math.floor(number / 100)] + " Hundred ";
number = number % 100;
}
if (number >= 10 && number < 20) {
word += teens[number - 10] + " ";
} else {
word += tens[Math.floor(number / 10)] + " ";
word += units[number % 10] + " ";
}
return word.trim();
}
function convertNumberToWords() {
const numberInput = document.getElementById('numberInput').value;
const result = numberToWords(parseFloat(numberInput));
document.getElementById('result').innerText = result;
}
</script>
</body>
</html>
Explanation
- HTML Structure:
- A container with an input field to enter the number and a button to trigger the conversion.
- A
div
element to display the result.
- CSS Styles:
- Basic styling for the container, input, button, and result elements.
- JavaScript Functions:
numberToWords
: Converts a number to words.convertToWords
: Converts groups of three digits to words.convertHundreds
: Converts hundreds to words.convertNumberToWords
: Gets the number from the input field, callsnumberToWords
, and displays the result.
How to Use
- Open the HTML file in a web browser.
- Enter a number in the input field.
- Click the "Convert" button to see the number converted to words in the result area.
This example provides a simple and interactive way to convert numbers to words using HTML and JavaScript, suitable for integration into any web application.
Related Articles:
- Automatically Setting the Current Date and Time in an HTML Form
- How to Create a Spinner with Loading Data Percentage in DataTables
- Convert Numbers to Khmer Number System Words (HTML+JAVASCRIPT)
- Converting Numbers to Words in JavaScript
- Create Login Form Using HTML, CSS, JavaScript
- JavaScript – Create Notes App