Converting Numbers into Words with the power of HTML and JavaScript

CONVERT NUMBER TO WORDS Write a simple JavaScript program that converts a number to words. Include an HTML page where the user can input the number to be converted. The conversion process should involve using both for loops and switch statements.

Answer №1

Here is a useful piece of code that can help you convert numbers to words easily.

var num = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split(" ");
var tens = "twenty thirty forty fifty sixty seventy eighty ninety".split(" ");

function numberToWords(n){
    if (n < 20) return num[n];
    var digit = n%10;
    if (n < 100) return tens[~~(n/10)-2] + (digit? "-" + num[digit]: "");
    if (n < 1000) return num[~~(n/100)] +" hundred" + (n%100 == 0? "": " and " + numberToWords(n%100));
    return numberToWords(~~(n/1000)) + " thousand" + (n%1000 != 0? " " + numberToWords(n%1000): "");
}

Check out this link for more information on how to convert numbers to words in JavaScript

Answer №2

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <br><br>
    <h1>CONVERT NUMBER TO WORDS</h1>
    <input type="number" id="nm1" placeholder="Enter a number"><br><br>
    <input type="button" value="Convert to Words" id="optin" onclick="convertToWords()">
    <p id="result" style="color: blueviolet;"></p>

    <script>
        function convertToWords() {
            var inputNumber = document.getElementById("nm1").value
            var strNumber = String(inputNumber)
            for (let i = 0; i < strNumber.length; i++) {
                switch (strNumber[i]) {
                    case "1":
                        document.getElementById("result").innerHTML += "one"+" " 
                        break
                    case "2":
                        document.getElementById("result").innerHTML += "two"+" "
                        break
                    case "3":
                        document.getElementById("result").innerHTML += "three"+" "
                        break
                    case "4":
                        document.getElementById("result").innerHTML += "four"+" "
                        break
                    case "5":
                        document.getElementById("result").innerHTML += "five"+" "
                        break
                    case "6":
                        document.getElementById("result").innerHTML += "six"+" "
                        break
                    case "7":
                        document.getElementById("result").innerHTML += "seven"+" "
                        break
                    case "8":
                        document.getElementById("result").innerHTML += "eight"+" "
                        break
                    case "9":
                        document.getElementById("result").innerHTML += "nine"+" "
                        break
                    case "0":
                        document.getElementById("result").innerHTML += "zero"+" "
                        break
                    default :
                        document.getElementById("result").innerHTML = "Please enter a valid number/digit"
                }
            }
        }
    </script>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with unrecognized expression in JQuery when processing Ajax response

Recently, I implemented a JQuery Ajax Form on my website. $('#modal-body-sign-in').on('submit', '#sign-in', function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr(&apo ...

What is the best way to retrieve ember model relation properties within routes and controllers?

Currently using ember 2.7.0, I am facing an issue while setting up my ember app with a currentUser.organization derived from the authenticated token. Although I can successfully resolve the currentUser, I am encountering difficulties in resolving the prope ...

The function 'downloadFunc' is not recognized as a valid function within the context of ReactJS custom hooks

Here is a unique custom hook that triggers when the user presses a button, calling an endpoint to download files as a .zip: import { useQuery } from 'react-query'; import { basePath } from '../../config/basePath'; async function downlo ...

Currently struggling to retrieve data from an AJAX post request within a C# controller

I need assistance with sending data from JavaScript to a C# controller using AJAX. However, I am facing an issue where all the arguments in the Add method of my controller are showing up as null. Below is my AJAX code: function sendRequest(name, price, ab ...

What is the best way to generate conditional test scenarios with Protractor for testing?

Currently, there are certain test cases that I need to run only under specific conditions. it ('user can successfully log in', function() { if(siteAllowsLogin) { ..... } The problem with the above approach is that even when sitesNo ...

retrieve information in json format from a specified web address

I need to figure out why the data from a specific URL is not being displayed properly on my node application. It seems like there might be an error in my code. const extractRefDefaultSchema = async (data) => { const url = "https://mos.esante.gouv.f ...

Display checkboxes on all TableRow elements as soon as one of them is checked

I've incorporated a material-ui Table into my project and have successfully implemented multi-select functionality. Here are the requirements I've fulfilled so far: Checkboxes are initially hidden - COMPLETED Hovering over a row reveals its che ...

Is there a way to print messages to the console of openDevTools in Electron JS?

After finishing a hello world application using electron js, I have successfully printed to my terminal with console.log and opened the openDevTools in the window of my application. However, I am now interested in finding a way for my console.log stateme ...

What is the best method to set one div as active by default in jQuery UI Accordion?

$(window).load(function(){ $.fn.togglepanels = function(){ return this.each(function(){ $(this).addClass("ui-accordion ui-accordion-icons ui-widget ui-helper-reset") .find("h3") .addClass("ui-accordion-header ui-helper-reset ...

Adjust the size of the div to fit its content while maintaining the transition animation

I am aiming for the DIV height to automatically adjust to the text within it, while also maintaining a minimum height. However, when the user hovers their mouse over the DIV, I want the height to change smoothly without losing the transition effect. When ...

Troubleshooting problems encountered when duplicating an array in JavaScript

I am attempting to utilize properties and flatmap to modify an array without altering the original data. I have implemented this method in two different instances within a single dispatch call in Vue.js when transferring data from parent to children comp ...

Is there a way to display the output of jQuery in an input box rather than a span?

I need to display the result of this function in an input box instead of a span tag because I plan to utilize the result in the following form. function checkChange(){ $.ajax({ url: "ordercalculate.php", data: $('form').seria ...

Utilize Javascript and JQuery to implement sending a custom header in an OPTIONS preflight API request

Snippet: $.ajax({ type: 'GET', dataType: 'json', url: api, xhrFields: { withCredentials: true }, beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', "Basic [my auth token]"); }, ...

What is the process for adding to a highly nested array in mongoose?

Here is the Model I am working with: const MessagesSchema = mongoose.Schema({ //for individual message text: { type: String, required: true } }, { timestamps : true }) const MessagesCollectionSch ...

Enhance tick labels in C3.js with supplementary information

I need a specific format for the tick: tick: { fit: true, multiline: false, outer: false, format: function (x) { var value = this.api.ca ...

Incorporating a division using the data() method

Currently, I am in the process of generating a list of flash SWFs. The data for this list is retrieved through an ajax call, which returns a JSON object. To populate the rows with data, I utilize my makeAppRow function. makeAppRow = function(myData) { ...

When making an Ajax post request, the loading indicator may not appear

I've implemented the jQuery code below for an autocomplete input field, but I'd like to have a spinner display while waiting for the response from the server. In my code, I'm using search: to show the loading div and open: to hide it. The s ...

Only if there is an update in the SQL database, I wish to refresh the div

I have created a voting system and I am facing an issue with the data updating. I have implemented a setInterval function in javascript to load the data every 2 seconds, but it's not working as expected. There are no errors shown, but the data is not ...

Extract the property value and save it as an array in Vue

Looking to extract all values of a specific property and save them as an array. I attempted the following method: data() { return { roomList: null } }, methods: { getRooms() { var that = this axios.get('http://local ...

Tips for choosing the node_modules distribution flavor to include in your webpack bundle

Issue: Following the update of AJV.js to Version 6.4, my vendor bundle now includes the "uri-js" ESNEXT version instead of the ES5 version, causing compatibility issues with IE11. Analysis: Upon investigation, I discovered that AJV references uri-js usi ...