How to Convert Number into Words in Javascript
In this tutorial, you will learn how to convert number into words in javascript. It is not easy to convert a number to words and you may need to write some sort of complex function to get it done. If you are a pro javascript developer, then definitely it is possible, but not for newbies.
To solve such problem, there are a bunch of libraries written by a lot of javascript developers. We are going to use one of them to accomplish our goal. The library that we are going to use is number-to-words because it is very simple and easy to use.
In the following example, we will enter some random number in the input field and upon click of a button, we will convert that number into words and display it on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have a few elements in the HTML file and that includes
div
,button
,input
, andh1
. Thediv
element with a class ofcontainer
is just a wrapper for the rest of the elements. - The inner text for the
button
element is“Convert”
and for theh1
element, it is“Output”
. - We have downloaded the
number-to-words
library and included it in the HTML file using thescript
tag at the bottom. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div class="container"> <div> <input type="text"> <button>Convert</button> </div> <h1>Output</h1> </div> <script src="numberToWords.js"></script> <script src="script.js"></script> </body> </html>
.container { display: flex; flex-direction: column; align-items: center; }
Javascript
- We have selected 3 elements
button
,input
, andh1
usingdocument.querySelector()
method and stored them inbtnConvert
,input
, andoutput
variables respectively. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are using the
toWords()
method of thenumber-to-words
library and passing the value of theinput
element as a parameter. - We are displaying the conversion result in the
h1
element using theinnerText
property.
let btnConvet = document.querySelector('button'); let input = document.querySelector('input'); let output = document.querySelector('h1'); btnConvet.addEventListener('click', () => { output.innerText = numberToWords.toWords(input.value); });