Automatically add Commas to a Number in a TextBox

Posted by: Suprotim Agarwal , on 1/23/2015, in Category jQuery and ASP.NET
Views: 186805
Abstract: This article demonstrates how to use jQuery and Globalize.js to represent a number in textbox depending on the user' culture.

Different cultures have different ways of representing Dates, Numbers, Currencies, and Measurements etc. So Christmas day in India is represented as 25/12/2014 (dd/MM/YYYY) whereas the same is represented as 12/25/2014 (M/d/yyyy) in North America and some other parts of the world.

Similarly different parts of the world represent Numbers using different symbols. In the US, commas and decimals are used to represent a number like 10000.20 as 10,000.20. However the same number in Europe is represented as 10.000,20.

JavaScript is not a culture-aware programming language. Although JavaScript understands the English culture’s decimal formatting, however it does not know how to use a culture’s number separator. Users have worked around this limitation by programmatically determining culture information from the browser’s navigator object; and representing dates and numbers accordingly. However the approach is not very consistent due to browser inconsistencies.

 

There are various scripts that can be found on the internet that allows you to automatically add commas to a number. Create a HTML file called ‘NumberFormatting.html’ using Visual Studio or any other web editor of your choice and use the following markup:

<input id="num" type="text" />
<input type="button" id="btnformat" value="Format Number" />

We have added a textbox and a button control to the page. Now add the following script (by a programmer Elias Z) that adds a comma to a number after every three digits:

 

$(function () {
    $('#btnformat').on('click', function () {
        var x = $('#num').val();
        $('#num').val(addCommas(x));
    });
});

function addCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}

The script uses a regular expression to add commas. Passing a number like 23456789.12345 produces 23,456,789.12345, which is the desired result.

Live Demo: http://www.jquerycookbook.com/demos/S2-InputControls/12-NumberFormatting.html

The script we saw works fine, but what if at a later date, you want to represent the same number for different countries?

Although JavaScript does not understand a culture’s number separator, it can certainly format numbers based on a certain culture. It does so by using the Number.prototype.toLocaleString() method. This method allows you to convert a number to a string that is formatted with local numeric formatting settings.

var num = 23456789.12345;
num = num.toLocaleString();
console.log(num);

The following code produces the output 23,456,789.123.

Using Globalize.js to format Numbers

Although the approaches shown above work, to handle such scenarios, using a well-tested library function is the way to go. When your application changes in the future to accommodate international users, handling internationalization issues becomes a nightmare without a library function. This is where the Globalize.js library comes handy!

Globalize.js (https://github.com/jquery/globalize) is an open source JavaScript library for internationalization and localization and supports over 350 different cultures. It was created originally by Microsoft and contributed to the jQuery library with the name jQuery globalization plug-in. Later it was made a standalone library.

It’s worth noting that Globalization is a native feature in JavaScript with EcmaScript 5.1 and above. Read http://www.ecma-international.org/ecma-402/1.0/#sec-8 to learn more about the ECMAScript Internationalization API Specification.

Create a HTML file called ‘1-NumberFormatting.html’. Download the Globalize files from https://github.com/jquery/globalize . Look for the Download ZIP button on the right hand side of the page and click it to download a .zip archive. Extract the files from the archive and copy the lib/globalize.js and lib/cultures/globalize.cultures.js in the scripts folder. globalize.js deals with localization whereas globalize.cultures.js contains a complete set of the locales (around 352 different cultures are supported as of this writing).

The globalize.culture.js file is around 850 KB. If you are dealing with only a selected few regions, it is advisable to use only those culture files found in the lib/cultures folder. For eg: if you are planning to target only India and US locales, then you can directly reference the globalize.culture.en-IN.js and globalize.culture.en-US.js files in your application to save some server bandwidth.

Now reference these two files in your application as shown here:

<script src="../scripts/globalize.js"></script>
<script charset="utf-8" src="../scripts/globalize.cultures.js"></script>

Add the following HTML which contains some Labels, a DropDown and a TextBox to show the formatted number.

<body>
    <p id="para"></p>
    <label for="ddlculture">Select Region</label>
    <select id="ddlculture">
        <option></option>
        <option value="zh-TW">China</option>
        <option value="fr-FR">France</option>
        <option value="de-DE">Germany</option>
        <option value="en-IN">India</option>
        <option value="ja-JP">Japan</option>
        <option value="ru-RU">Russia</option>
        <option value="es-ES">Spain</option>
        <option value="en-GB">United Kingdom</option>
        <option value="en-US">United States</option>
    </select>
    <label for="txtNum">Formatted Number: </label>
    <input type="text" id="txtNum" readonly="true" />
</body>

Now use this simple piece of code that uses the Globalize.js library to format a number depending on the country the user has selected from the dropdown.

$(function () {
    var number = 1234567.89;
    $("#para").html("Original Number: " + number);

    $('#ddlculture').on('change', function () {
        var culture = $(this).val();
        var formattedNumber = formatNumber(number, culture);        
        $("#txtNum").val(formattedNumber);
    });

    function formatNumber(num, currentculture) {
        Globalize.culture(currentculture);
        if (isNaN(num))
            return('Number not valid');
        return (Globalize.format(num, "n2"));
    }
});

In the code above, we are tracking the change event of the dropdown control and capturing the culture of the selected dropdown list item. This is possible as the value attribute of each dropdown list item has the culture defined; for eg: <option value="en-IN">India</option>. The original number to be formatted and the culture, is passed to the formatNumber() function which uses the Globalize.format() function to return the formatted number. It’s that simple!

Run the code and you will get the formatted number based on the option selected.

s4-number-globalize

Similarly Globalize.js also formats a date using the given format and locale. I will recommend you to read the documentation at https://github.com/jquery/globalize#date for some handy examples.

Live Demo: http://www.jquerycookbook.com/demos/S2-Input Controls/ 12.1-NumberFormatting.html

I hope this article helped! You can also check out several other performance tips in my new book www.jquerycookbook.com

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Fifteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!