Create a Number to Words Converter in HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to build a user-friendly Number to Words converter using HTML, CSS, and JavaScript. Perfect for beginners!


Create a Number to Words Converter in HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

In today's digital landscape, web developers and designers are constantly seeking innovative ways to engage and captivate their website visitors. One such way is by integrating interactive tools and features that not only enhance user experience but also provide valuable functionalities. In this tutorial, we will embark on a journey to create a powerful yet beginner-friendly web tool: a Number to Words converter. By combining the prowess of HTML, the elegance of CSS, and the functionality of JavaScript, you'll learn how to transform numeric input into words effortlessly.

In the age of user-centric design, such tools hold immense value. Imagine a scenario where your website visitors can input numeric data, and with a simple click, see those numbers eloquently translated into words. Whether you're a seasoned developer looking to expand your skillset or a complete beginner taking your first steps into the world of web development, this guide is designed to be accessible to all. No prior coding experience is required, making it a perfect starting point for your journey into web development.

Throughout this tutorial, we'll take you by the hand and guide you through each step, providing clear explanations and code examples. By the end, you'll not only have a fully functional Number to Words converter at your disposal but also the skills and confidence to implement similar interactive features on your website, taking your web development prowess to new heights. Let's begin this exciting journey of turning numbers into words with the power of HTML, CSS, and JavaScript!

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our number to words converter.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let me explain each part of the code in English:

1. <!DOCTYPE html>: This is a declaration specifying the document type and version of HTML being used, which is HTML5 in this case.

2. <html lang="en">: This is the opening tag for the HTML document. It specifies that the content is in the English language (the "en" attribute).

3. <head>: This section contains metadata about the web page, such as character encoding, viewport settings, and external resources. It does not display any content on the page itself.

  • <meta charset="UTF-8">: This specifies that the character encoding used for the page is UTF-8, which includes a wide range of characters and symbols.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: This is a directive for Internet Explorer to use the latest rendering engine.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: This meta tag sets the viewport width to the device width and sets the initial scale to 1.0, which helps in making the web page responsive on various devices.
  • <title>Number To Words Converter</title>: This is the title of the web page, which is displayed in the browser's title bar or tab.
  • <link rel="stylesheet" href="styles.css">: This line links an external CSS stylesheet named "styles.css" to the HTML document. It's used for styling the page's content.

4. <body>: This is the main content of the web page that will be visible to the user.

5. <div class="container">: This is a container div that wraps the entire content of the page. It's often used for layout purposes.

6. <div class="header">: This div contains the heading of the project, which is enclosed within an <h1> tag. It appears to be the title of the web application.

7. <div class="input">: This div represents the input section of the application.

  • <h3 class="input-text">Enter Number</h3><br>: This is a subheading that instructs the user to enter a number.
  • <input id="input-box" placeholder="eg., 123" oninput="getValue()">: This is an input field where the user can enter a number. It has an ID ("input-box") and an "oninput" attribute that specifies a JavaScript function ("getValue()") to be executed when the user types into this input field.

8. <div class="output">: This div represents the output section of the application.

  • <h3 class="convert-text">Converted In Words</h3>: This is a subheading indicating that the result will be displayed in words.
  • <div class="output-box">: This is a container for displaying the converted number in words. Initially, it appears to be empty.

9. <script src="script.js"></script>: This line includes an external JavaScript file named "script.js." It's used to provide interactivity to the web page, for the conversion of numbers to words.

This is the basic structure of our number-words converter using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the number to words converter is in place, the next step is to add styling to the converter using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our converter.

Let's break down the code section by section:

1. Default settings:

  • The * selector applies these styles to all elements on the page.
  • It sets the margin and padding to 0 for all elements and gives a default background-color of #6cFE.

2. .container:

  • Styles for a container element.
  • It's positioned absolutely and takes up 70% of the width and 80% of the height of its parent.
  • Has a light yellow background color and rounded corners.

3. .header:

  • Styles for a header element inside the container.
  • Positioned relative to its normal position.
  • It's 10% from the top of its container and 20% from the left.
  • Takes up 60% of the width and 10% of the height of its container.
  • It appears to have no background color (transparent) and has rounded corners.

4. .heading:

  • Styles for a heading element inside the header.
  • The text is centered.
  • The font is cursive, and the text color is white.
  • It has rounded corners.

5. .input:

  • Styles for an input container.
  • Positioned relative to its normal position.
  • It's 12% from the top and 5% from the left of its container.
  • Takes up 88% of the width and 33% of the height of its container.
  • Has a light yellow background color and rounded corners.
  • Uses flex to horizontally center its content.

6. .input-text:

  • Styles for text inside the input container.
  • It's absolutely positioned.
  • The font size is 2.4rem, and the text color is black.
  • The background color is light yellow, and the font is cursive.

7. #input-box:

  • Styles for an input box with the ID "input-box."
  • It's padded, relatively positioned, and 40% from the top and 1% from the left of its container.
  • Has a fixed height and width.
  • Rounded corners, a font size of 2rem, and a cursive font-family.
  • A 2px solid light black border.

8. input, textarea:

  • Applies the light yellow background color to all input and textarea elements.

9. .output:

  • Styles for an output container similar to the input container.
  • Positioned relatively.
  • 14% from the top and 5% from the left of its container.
  • Takes up 88% of the width and 33% of the height.
  • Has a light yellow background and rounded corners.
  • Uses flex to center its content.

10. .convert-text:

  • Styles for text inside the output container.
  • Absolutely positioned.
  • Font size of 2.4rem, black text color, light yellow background, and cursive font-family.

11. .output-box:

  • Styles for an output box inside the output container.
  • Positioned relatively.
  • 40% from the top, with a fixed height.
  • Light yellow background.

12. p:

  • Styles for paragraph elements.
  • Light yellow background, cursive font-family, 2rem font size, and centered text alignment.

This will give our number to words converter an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

/* Default settings */
* {
  margin: 0;
  padding: 0;
  background-color: #6cFE;
}

.container {
  position: absolute;
  top: 10%;
  left: 15%;
  width: 70%;
  height: 80%;
  background-color: lightyellow;
  border-radius: 1rem;
}

.header {
  position: relative;
  top: 5%;
  left: 20%;
  width: 60%;
  height: 10%;
  background-color: none;
  border-radius: 0.5rem;
}

.heading {
  text-align: center;
  font-family: cursive;
  color: white;
  border-radius: 0.5rem;
}

/* CSS style of input box */
.input {
  position: relative;
  top: 12%;
  left: 5%;
  width: 88%;
  height: 33%;
  background-color: lightyellow;
  border-radius: 0.8rem;
  display: flex;
  justify-content: center;
}

.input-text {
  position: absolute;
  font-size: 2.4rem;
  color: black;
  background-color: lightyellow;
  font-family: cursive;
}

#input-box {
  padding: 8px;
  position: relative;
  top: 40%;
  left: 1%;
  height: 3rem;
  width: 19rem;
  border-radius: 0.6rem;
  font-size: 2rem;
  font-family: cursive;
  border: 2px solid lightblack;
}

input,
textarea {
  background-color: lightyellow;
}

/* CSS style of Output box */
.output {
  position: relative;
  top: 14%;
  left: 5%;
  width: 88%;
  height: 33%;
  background-color: lightyellow;
  border-radius: 0.8rem;
  display: flex;
  justify-content: center;
}

.convert-text {
  position: absolute;
  font-size: 2.4rem;
  color: black;
  background-color: lightyellow;
  font-family: cursive;
}

.output-box {
  position: relative;
  top: 40%;
  height: 20%;
  background-color: lightyellow;
}

p {
  background-color: lightyellow;
  font-family: cursive;
  font-size: 2rem;
  text-align: center;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript.

Here's a step-by-step explanation of the code:

1. Four arrays are defined at the beginning of the code to assist in the conversion:

  • digit: An array that maps digits (0-9) to their corresponding names.
  • denominations: An array representing different denominations (e.g., Thousand, Million, Billion, Trillion).
  • tens: An array representing special names for numbers between 10 and 19.
  • ties: An array representing tens places (e.g., Ten, Twenty, Thirty).

2. HTML elements are accessed using JavaScript, specifically:

  • inputBox: It refers to an input element with the ID "input-box."
  • outputBox: It refers to the first <p> element in the HTML document.

3. The getValue function is the main function that gets called when the user submits input. It performs the following steps:

  • Retrieves the user input from the inputBox.
  • Validate the input to ensure it contains only digits and is not longer than 15 characters.
  • If the input is valid, it proceeds with the conversion process.
  • Padding is added to the input with leading zeros to make its length divisible by 3.
  • The input is reversed for easier processing.
  • It checks if the input is zero and handles it accordingly.
  • Calls the convert function with initial index 0 and level 0.

4. The convert function is a recursive function that converts a group of three digits (hundreds, tens, ones) into words. It takes two parameters:

  • idx: The index in the input string where the conversion should start.
  • level: The current level of denomination (e.g., Thousand, Million).

5. Inside the convert function:

  • It handles the hundreds, tens, and one's digits separately and adds their word representations to the cur variable.
  • The appropriate denomination (e.g., Thousand, Million) is added to cur based on the current level.
  • The function is called recursively with updated index and level values.
  • The add function is used to concatenate strings while handling empty strings correctly.

6. The add function simply concatenates two strings, adding a space between them if both strings are non-empty.

7. The reverseString function is used to reverse the input string, making it easier to process groups of three digits from right to left.

8. The final word representation of the input number is displayed in the outputBox element.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

// An array that maps digits to their corresponding names
var digit = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"];

// An array that represents different denominations (e.g., Thousand, Million, Billion, Trillion)
var denominations = ["", "Thousand", "Million", "Billion", "Trillion"];

// An array that represents special names for numbers between 10 and 19
var tens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];

// An array that represents tens places (e.g., Ten, Twenty, Thirty, Forty)
var ties = ["Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];

// Getting the HTML elements by their IDs
let inputBox = document.getElementById('input-box');
let outputBox = document.getElementsByTagName('p')[0];

// Variable to store the user input
var input;

// Function that gets called when the user submits the input
function getValue() {
    // Getting the input from the input box
    input = inputBox.value;

    // Conditions to check the validity of the input
    // Checks if the input contains only digits
    // and if its length is not greater than 15
    if (!/^\d+$/.test(input) && input.length > 0) {
        outputBox.innerHTML = "Invalid input. Please enter only digits.";
        outputBox.style.color = 'red';
        return;
    } else if (input.length > 15) {
        outputBox.innerHTML = "Too Large Number.";
        outputBox.style.color = 'red';
        return;
    }

    // Resetting the output box style and content
    outputBox.style.color = 'black';
    outputBox.innerHTML = "";

    // Padding the input with leading zeros until its length is divisible by 3
    while (input.length % 3 !== 0) {
        input = "0" + input;
    }

    // Reversing the input string
    input = reverseString(input);

    // Checking if the input is zero
    if (input === "000")
        outputBox.innerHTML = "Zero";
    else
        // Calling the conversion function with initial index and level values
        outputBox.innerHTML = convert(0, 0);
}

// Function to concatenate two strings
function add(s1, s2) {
    if (s1.length && s2.length)
        return s1 + " " + s2;
    return s1 + s2;
}

// Main recursive function for converting the input to words
function convert(idx, level) {
    // Base case: if the index is greater than or equal to the input length, return an empty string
    if (idx >= input.length)
        return "";

    let cur = ""; // Variable to store the current word representation of the digits at the current index

    let od = parseInt(input[idx]); // One's digit
    let td = parseInt(input[idx + 1]); // Ten's digit
    let hd = parseInt(input[idx + 2]); // Hundred's digit

    // Handling the hundred's digit
    if (hd)
        cur = add(cur, add(digit[hd], "Hundred"));

    // Handling the ten's and one's digits
    if (td) {
        if (td == 1)
            cur = add(cur, tens[od]);
        else {
            cur = add(cur, ties[td - 1]);
            if (od) cur = add(cur, digit[od]);
        }
    } else if (od)
        cur = add(cur, digit[od]);

    // Adding the appropriate denomination based on the current level
    if (cur != "")
        cur = add(cur, denominations[level]);

    // Recursively calling the convert function with updated index and level values
    return add(convert(idx + 3, level + 1), cur);
}

// Function to reverse a string
function reverseString(str) {
    return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}

Final Output:

Create a Number to Words Converter in HTML, CSS, and JavaScript.gif

Conclusion:

In conclusion, you've successfully learned how to create a Number to Words converter using HTML, CSS, and JavaScript. This tutorial has provided you with a comprehensive guide, starting from the basics and gradually building up to a fully functional web tool.

You began by understanding the importance of such a converter on a website and the prerequisites for this project, ensuring that beginners can follow along without any difficulty.

You then delved into the HTML structure, creating the necessary input fields and output areas, setting the foundation for the converter. The CSS styling section allowed you to personalize the converter's appearance, making it seamlessly integrate with your website's design.

The JavaScript implementation was the heart of this project, where you learned how to convert numbers to words and handle various scenarios, including both positive and negative numbers.

Now, armed with this knowledge, you can enhance your web development skills and create interactive tools that engage your website visitors. We encourage you to experiment further, add additional features, and make this converter truly your own.

Remember, web development is all about creativity and innovation. So, go ahead, implement your Number to Words converter, and make your website stand out. Thank you for joining us on this coding journey, and we look forward to seeing the amazing projects you'll create. Happy coding!

Credit: Avdhesh Varshney

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺