Convert Number to Words using Javascript, Jquery, ReactJS, and Typescript

Updated by shortbuzz

Convert Number to Words

We will learn how to create a function that accepts a number and convert numbers to words in javascript, typescript and jquery

We will also show you the output of convert 1 to one in JavaScript and convert amount in words using JavaScript Indian rupees and to convert number to lakhs javascript

convert number to words javascript and Jquery

The code below converts decimal numbers to words. This code is compatible with both jquery and Javascript.

function convertNumberToWords(num) {
  let singleDigit = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
  let specialNumbers = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
  let tens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
  let scales = ['', 'thousand', 'million', 'billion', 'trillion'];

  num = num.toString();
  num = num.replace(/[\, ]/g, '');
  if (num !== parseFloat(num)) return 'not a number';

  let decimalIndex = num.indexOf('.');
  if (decimalIndex === -1) decimalIndex = num.length;
  if (decimalIndex > 15) return 'too big';

  let digits = num.split('');
  let result = '';
  let useScales = 0;

  for (let i = 0; i < decimalIndex; i++) {
    if ((decimalIndex - i) % 3 === 2) {
      if (digits[i] === '1') {
        result += specialNumbers[Number(digits[i + 1])] + ' ';
        i++;
        useScales = 1;
      } else if (digits[i] !== 0) {
        result += tens[digits[i] - 2] + ' ';
        useScales = 1;
      }
    } else if (digits[i] !== 0) {
      result += singleDigit[digits[i]] + ' ';
      if ((decimalIndex - i) % 3 === 0) result += 'hundred ';
      useScales = 1;
    }

    if ((decimalIndex - i) % 3 === 1) {
      if (useScales) result += scales[(decimalIndex - i - 1) / 3] + ' ';
      useScales = 0;
    }
  }

  if (decimalIndex !== num.length) {
    let endIndex = num.length;
    result += 'point ';
    for (let i = decimalIndex + 1; i < endIndex; i++) result += singleDigit[digits[i]] + ' ';
  }

  result = result.replace(/\number+/g, ' ');
  return result.trim() + '.';
}

//Call the function
let number = 52642;
console.log(convertNumberToWords(number));

Output

//The function would convert the number 526 to "five hundred twenty six."
>> console.log(convertNumberToWords(526));
< five hundred twenty six.

>> console.log(convertNumberToWords(3.84));
< three point eight four.

//convert 1 to one in JavaScript
>> console.log(convertNumberToWords(1));
< one

//convert numbers to words in lakh
>> console.log(convertNumberToWords(8433484));
< eight million four hundred thirty-three thousand four hundred eighty-four.

//passing the invalid number or text it returns not a number
>> console.log(convertNumberToWords("world"));
< not a number

Convert number to words reactjs

import React, { useState } from 'react';

function ConvertNumberToWords({ num }) {
  let singleDigit = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
  let specialNumbers = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
  let tens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
  let scales = ['', 'thousand', 'million', 'billion', 'trillion'];

  num = num.toString();
  num = num.replace(/[\, ]/g, '');
  if (num !== parseFloat(num)) return 'not a number';

  let decimalIndex = num.indexOf('.');
  if (decimalIndex === -1) decimalIndex = num.length;
  if (decimalIndex > 15) return 'too big';

  let digits = num.split('');
  let result = '';
  let useScales = 0;

  for (let i = 0; i < decimalIndex; i++) {
    if ((decimalIndex - i) % 3 === 2) {
      if (digits[i] === '1') {
        result += specialNumbers[Number(digits[i + 1])] + ' ';
        i++;
        useScales = 1;
      } else if (digits[i] !== 0) {
        result += tens[digits[i] - 2] + ' ';
        useScales = 1;
      }
    } else if (digits[i] !== 0) {
      result += singleDigit[digits[i]] + ' ';
      if ((decimalIndex - i) % 3 === 0) result += 'hundred ';
      useScales = 1;
    }

    if ((decimalIndex - i) % 3 === 1) {
      if (useScales) result += scales[(decimalIndex - i - 1) / 3] + ' ';
      useScales = 0;
    }
  }

  if (decimalIndex !== num.length) {
    let endIndex = num.length;
    result += 'point ';
    for (let i = decimalIndex + 1; i < endIndex; i++) result += singleDigit[digits[i]] + ' ';
  }

  result = result.replace(/\number+/g, ' ');
  return result.trim() + '.';
}

function App() {
  const [number, setNumber] = useState(52642);

  return (
    <div>
      <input type="text" value={number} onChange={e => setNumber(e.target.value)} />
      <p>{ConvertNumberToWords({ num: number })}</p>
    </div>
  );
}

export default App;

Convert numbers to words in TypeScript and Angular

Let's rewrite the code to convert numbers to English words in TypeScript. The following code is compatible with TypeScript and Angular.

function convertNumberToWords(num: number | string): string {
  const singleDigit = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
  const specialNumbers = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
  const tens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
  const scales = ['', 'thousand', 'million', 'billion', 'trillion'];

  const numStr = num.toString();
  const withoutComma = numStr.replace(/[\, ]/g, '');
  if (!Number(withoutComma)) return 'not a number';

  const decimalIndex = withoutComma.indexOf('.');
  if (decimalIndex === -1) decimalIndex = withoutComma.length;
  if (decimalIndex > 15) return 'too big';

  const digits = withoutComma.split('');
  let result = '';
  let useScales = 0;

  for (let i = 0; i < decimalIndex; i++) {
    if ((decimalIndex - i) % 3 === 2) {
      if (digits[i] === '1') {
        result += specialNumbers[Number(digits[i + 1])] + ' ';
        i++;
        useScales = 1;
      } else if (digits[i] !== '0') {
        result += tens[Number(digits[i]) - 2] + ' ';
        useScales = 1;
      }
    } else if (digits[i] !== '0') {
      result += singleDigit[Number(digits[i])] + ' ';
      if ((decimalIndex - i) % 3 === 0) result += 'hundred ';
      useScales = 1;
    }

    if ((decimalIndex - i) % 3 === 1) {
      if (useScales) result += scales[(decimalIndex - i - 1) / 3] + ' ';
      useScales = 0;
    }
  }

  if (decimalIndex !== withoutComma.length) {
    const endIndex = withoutComma.length;
    result += 'point ';
    for (let i = decimalIndex + 1; i < endIndex; i++) result += singleDigit[Number(digits[i])] + ' ';
  }

  result = result.replace(/\s+/g, ' ');
  return result.trim() + '.';
}

Explantionation to above code

A number is passed as a parameter to the function convertNumberToWords, which transforms the number to words. The words are presented as a string in the English language.

The function first defines arrays of single digits, special numbers (for integers between 10 and 19), tens, and scales (for multiples of thousands such as million, billion, trillion).

The function then transforms the number into a string, removes any commas or spaces, and determines whether the output is still a number by testing it for validity. It returns the string "not a number" if it is not a valid number.

The next step is for the function to determine whether the number has a decimal point and whether it is too lengthy (more than 15 digits).

The function then loops through each digit of the number and adds the relevant English word to a result string. The special number for that two-digit number is added if a digit is 1 and the following digit is between 0 and 9. If the digit is neither 1 nor 0, it adds the equivalent word of tens or single digits. If the number is 0, nothing happens.

Finally, the code inserts any decimal part of the number and returns the result string, removing any extra spaces and adding a period at the end.

Summary

When a number is entered into the convertNumberToWords function, it is converted to a string, removed of any commas or spaces, checked to see if it is a valid number, and if it is, it is converted to words by breaking it down into individual digits and using arrays of words for single digits, special numbers, tens, and scales to build the result string. The string "not a number" is returned if the input is an invalid number. The function outputs a string with the final word ended by a period.

More articles from shortbuzz

ecommece template tailwindcss text and businessman
Technology

Get Free TailwindCSS eCommerce Template: Build Online Store

TailwindCSS eCommerce template free: Take advantage of our template & boost your online store's sales with a visually stunning and user-friendly website design continue reading

OpenAI logo chatgpt
Technology

How to block ChatGPT from access the content of your website

By adding code to robots.txt, .htaccess or Nginx server, you can stop ChatGPT from access or crawl your website content that is being used for AI training data continue reading

Google sign-in button and Google logo
Technology

How to migrate from Google Sign-In API to Identity Services

Use Google Identity Services API to improve the user experience & security of your website. Replace old Google Sign-In API with new method: Full migration guide continue reading

flower with cards
Technology

TailwindCSS: Show More/Less Truncate Text using JS & Reactjs

Use TailwindCSS, JavaScript or ReactJS to create a read more & show less function with a smooth transition using tailwind multi-line-clamp truncation continue reading

cloud server with laptop
Technology

Best web hosting service provider in Saudi Arabia (KSA)

Find the best web hosting service providers for your company in Saudi Arabia. Our detailed list includes the most cost-effective, reliable, and fast options. continue reading

Web hosting server and cloud hosting server
Technology

What is Web Hosting and Types: A Complete Beginners Guide

For creation of websites requires web hosting. Learn about many types and their advantages and disadvantages to select the best option for your website. continue reading

Using tailwind css align item in the centre of the screen text and tailwind logo
Technology

Tailwind CSS center div vertically and horizontally

Using tailwindCSS, place the div in the middle of the screen, both vertically and horizontally, using flexbox or grid system with simple explanation. continue reading

Xampp error windows
Technology

How to fix Error: MySQL shutdown unexpectedly in XAMPP

The cause of "Error: MySQL Shutdown Unexpectedly" in XAMPP, shutting down MySQL without running XAMPP as an administrator frequently leads to corruption. continue reading

Bootstrap icon and Tailwind css icon and grid layout design
Technology

How to make Tailwind CSS grid system like Bootstrap grids

Tailwind offers grid-template-column utility for creating basic grids, as well as the grid-cols-{size} & col-span-{size} utilities to create bootstrap-like grid continue reading

Python logo with folder icon and python code on computer screen in the background
Technology

Python Check If File Exists - Python Check If Directory Exists?

path.exists(path) method in python is used to check if a given file or directory exists or not; if it exists, it returns true or else return False continue reading