Learn how to convert a number to words in Javascript easily.

The goal of programming is the multiobjective optimization, we write code to automatize things that would take some time to do them manually. For many projects, you will need to convert a number to its words representation to prevent that the user writes the entire number into words (e.g the number 123456789 with words would be one hundred twenty-three million, four hundred fifty-six thousand, seven hundred eighty-nine). Yeah, that's a really long number and i know that you didn't even read the entire number, so, why would your user want to write it by himself ? Make this task easy for your users by automating it.

In this article you will learn to convert numbers to its words representation either with a library or using a single function.

A. Use a library

To convert numbers to words with Javascript, we are going to use the numberToWords package. This module contains some util methods for converting numbers into words, ordinal words and ordinal numbers.

You can install this module with npm executing (as this module is registered on npm, it works perfectly with Node.js too):

npm install number-to-words

Or if you use bower:

bower install number-to-words

In case that you don't use any package manager for Javascript, you can simply download the minified file of the repository here. Then in the browser the numberToWords variable will be globally accesible in the document and then include the numberToWords.min.js file in your document using a script tag:

<script type="text/javascript" src="/path/to/numberToWords.min.js"></script>

If you want more information about this project, visit the official repository in Github here.

Note

This library only converts integers numbers, any float value will be automatically parsed to integer.

Usage

The library provides 3 methods that allow you to convert an integer (or a number in string type) into words. Remember that you need to require the module in case you're using requireJS:

// If you're using Node.js or browserify (requireJS)
// require the module using:
var numberToWords = require('number-to-words');
numberToWords.toWords(13); // => “thirteen”


// If you're using the script in the browser
// then the global "numberToWords" variable will be accesible in the window
numberToWords.toOrdinal(1);
numberToWords.toWordsOrdinal(1);
numberToWords.toWords(1);

1. Converting a number to its abbreviated ordinal

You can convert the numbers to ordinals easily with this library, an ordinal number defines the position of something in a series, such as first, second, or third. Ordinal numbers are used as adjectives, nouns, and pronouns.

To convert a number to an abbreviated ordinal use the .toOrdinal method:

// 1st
numberToWords.toOrdinal(1);
// 2nd
numberToWords.toOrdinal(2);
// 3rd
numberToWords.toOrdinal(3);

// 1500th
numberToWords.toOrdinal(1500);
// 1234567890th
numberToWords.toOrdinal(1234567890);

The method return a string with the abbreviate ordinal value of the providen integer (or string) as first parameter.

2. Converting a number to its ordinal in words

Instead of use an abbreviation, numberToWords allows you to convert a number to an ordinal in words using the .toWordsOrdinal method:

// first
numberToWords.toWordsOrdinal(1);
// second
numberToWords.toWordsOrdinal(2);
// third
numberToWords.toWordsOrdinal(3);

// one thousand, five hundredth
numberToWords.toWordsOrdinal(1500);
// one billion, two hundred thirty-four million, five hundred sixty-seven thousand, eight hundred ninetieth
numberToWords.toWordsOrdinal(1234567890);

Pretty awesome and easy, isn't ?

3. Converting a number into words

You can convert a number easily to its words representation using the .toWords method:

// one
numberToWords.toWords(1);
// two
numberToWords.toWords(2);
// three
numberToWords.toWords(3);

// one thousand, five hundred
numberToWords.toWords(1500);
// one billion, two hundred thirty-four million, five hundred sixty-seven thousand, eight hundred ninety
numberToWords.toWords(1234567890);

Important note

This library supports the conversion up to 999999999999999 (15-digit number).

The usage of the library with a bigger number will inevitably lead to an exception Uncaught RangeError: Maximum call stack size exceeded that you can easily prevent using a try/catch statement.

B. Self implementation

If you don't want to use a library to achieve your goal and you only want to convert numbers to words using a simple snippet, then you can use the following simple function:

/**
 * Convert an integer to its words representation
 * 
 * @author McShaman (http://stackoverflow.com/users/788657/mcshaman)
 * @source http://stackoverflow.com/questions/14766951/convert-digits-into-words-with-javascript
 */
function numberToEnglish(n, custom_join_character) {

    var string = n.toString(),
        units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words;

    var and = custom_join_character || 'and';

    /* Is number zero? */
    if (parseInt(string) === 0) {
        return 'zero';
    }

    /* Array of units as words */
    units = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];

    /* Array of tens as words */
    tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];

    /* Array of scales as words */
    scales = ['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion'];

    /* Split user arguemnt into 3 digit chunks from right to left */
    start = string.length;
    chunks = [];
    while (start > 0) {
        end = start;
        chunks.push(string.slice((start = Math.max(0, start - 3)), end));
    }

    /* Check if function has enough scale words to be able to stringify the user argument */
    chunksLen = chunks.length;
    if (chunksLen > scales.length) {
        return '';
    }

    /* Stringify each integer in each chunk */
    words = [];
    for (i = 0; i < chunksLen; i++) {

        chunk = parseInt(chunks[i]);

        if (chunk) {

            /* Split chunk into array of individual integers */
            ints = chunks[i].split('').reverse().map(parseFloat);

            /* If tens integer is 1, i.e. 10, then add 10 to units integer */
            if (ints[1] === 1) {
                ints[0] += 10;
            }

            /* Add scale word if chunk is not zero and array item exists */
            if ((word = scales[i])) {
                words.push(word);
            }

            /* Add unit word if array item exists */
            if ((word = units[ints[0]])) {
                words.push(word);
            }

            /* Add tens word if array item exists */
            if ((word = tens[ints[1]])) {
                words.push(word);
            }

            /* Add 'and' string after units or tens integer if: */
            if (ints[0] || ints[1]) {

                /* Chunk has a hundreds integer or chunk is the first of multiple chunks */
                if (ints[2] || !i && chunksLen) {
                    words.push(and);
                }

            }

            /* Add hundreds word if array item exists */
            if ((word = units[ints[2]])) {
                words.push(word + ' hundred');
            }

        }

    }

    return words.reverse().join(' ');

}

And you can use easily:

// one hundred and twenty three million four hundred and fifty six thousand seven hundred and eighty nine
numberToEnglish(123456789);

// Use a custom separator (like , instead of "and")
// one hundred , twenty three million four hundred , fifty six thousand seven hundred , eighty nine
numberToEnglish(123456789, ",");

In the same way that the library, only a digit up to 15-digit is allowed. However, in this case this function won't throw an exception but the values that will generate in words will be not correct. Besides, this implementation doesn't support the conversion to ordinal.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors