Click here to Skip to main content
5,788,212 members and growing! (17,685 online)
Email Password   helpLost your password?
Web Development » Client side scripting » Controls     Intermediate License: The Code Project Open License (CPOL)

Format Currency using Javascript

By Carlos Saraiva Jr.

Format numbers to currency using Javascript
Javascript, C# 2.0, C# 3.0, C#, Dev

Posted: 21 Nov 2008
Updated: 21 Nov 2008
Views: 3,188
Bookmarked: 8 times
Note: This is an unedited reader contribution
Announcements
Loading...



Search    
Advanced Search
Sitemap
1 vote for this Article.
Popularity: 0.00 Rating: 3.00 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
1 vote, 100.0%
3
0 votes, 0.0%
4
0 votes, 0.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

This article describes how to format numbers to currency.

Background

These days I need format numbers in currency format and all I found searching net don't solve my problem. I found many good solutions, I use two as base. One in pt-br msdn forum and another in a javascript forum.

Using the code

I use the following code in a Textbox.

Before create methods, create a global variable named triggerFormat. triggerFormat is a Boolean and need to check if FormatString method is fired or no.

var triggerFormat = false;

In my code I use 3 client events: onkeydown, onkeypress and onkeyup.

In onkeydown event I use Backspace method to check if a backspace or delete was pressed:

function BackSpace(obj)
{
    var whichCode = (window.Event) ? event.which : event.keyCode;
    if (whichCode == 8 || whichCode == 46)
    {
        triggerFormat = true;
    }
    else
        return true;
}

In onkeypress event I use Money method to check if a digits or characters was pressed, if characters or some keys like return was pressed, nothing happens and FormatString method don't fire.

function Money()
{
    var whichCode = (window.Event) ? event.which : event.keyCode;
    if(whichCode == 0) return true;
    if(whichCode == 9) return true;
    if(whichCode == 13) return true;
    if(whichCode == 16) return true;
    if(whichCode == 17) return true;
    if(whichCode == 27) return true;
    if(whichCode == 34) return true;
    if(whichCode == 35) return true;
    if(whichCode == 36) return true;

    if(whichCode > 47 && whichCode < 58) 
        triggerFormat = true;
    else
        event.keyCode = 0;
}

In onkeyup event I use FormatString method to format numbers to currency

function FormatString(obj, quantityDecimals)
{
    var whichCode = (window.Event) ? event.which : event.keyCode;
    if(triggerFormat == true)
    { 
        var value = obj.value;
        value = value.replace(/\,/g, "");
        value = value.replace(/\./g, "");

        obj.value = MaskValue(value, quantityDecimals).FormatCurrency(quantityDecimals);
        triggerFormat = false;
        return false;
    }
    else
        return true;
}

In FormatString method the magic happens. I use a Maskvalue passing value and quantity decimals:

function MaskValue(value, quantityDecimals)
{
    var val2 = '';
    var len = value.length;
    var decimals = "";
    for(var i = 0; i < quantityDecimals; i++)
        decimals += "0";
    if(len == 0)
        return "0." + decimals;
    if(value.length <= decimals.length)
        return "0." + decimals.substring(0, decimals.length - value.length) + value;
    for(var j = 0; j < value.length; j++)
    {
        if(value.substring(0, 1) == "0" && (value.length > 5))
            value = value.substring(1, value.length);
    }
    var parte1 = value.substring(0, value.length - decimals.length);
    var parte2 = value.substring(value.length - decimals.length);
    var returnvalue = parte1 + "." + parte2;
    return returnvalue;
}

I using quantity decimals here to know length of this. In first for I mount decimals. First if is obvious. Second if is obvious too. I need create a second for to check left 0s because keyup event don't happen if you hold key, so when you release key check if exists left 0s. And after I simply divide the first and the second part to put a dot between them.

FormatCurrency need this:

function FormatMoney(c)
{
    var t = this;
    if(c == undefined)
        c = 2;
    var p, d = (t = t.split("."))[1].substr(0, c);
    for(p = (t = t[0]).length; (p -= 3) >= 1;)
        t = t.substr(0, p) + "." + t.substr(p);
    return t + "," + d + Array(c + 1 - d.length).join(0);
}

String.prototype.FormatCurrency = FormatMoney

So, this last method will format in currency and put the number of decimal desired.

Points of Interest

I believe that this code is better than the others because doesn't check the character typed and places by last beyond format.
Sorry for the bad english of all time, I hope I have helped. If there are any questions, suggestions for improvement, criticisms, please send.

History

This version is 1.0... version 2.0 coming soon...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Carlos Saraiva Jr.


Carlos Saraiva Jr. is a Developer and works with C#, VB, Javascript, ASP.NET, WPF, WCF, SQL Server 2005/2008, Oracle, in a Web, Windows Forms, Windows Services using Visual Studio 2005/2008.
Occupation: Software Developer
Location: Brazil Brazil

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
GeneralSandtrap controlmemberNuno Agapito12:02 21 Nov '08  
GeneralRe: Sandtrap controlmemberCarlos Saraiva Jr.1:11 22 Nov '08  
JokeNice articlememberNobruds8:03 21 Nov '08  
GeneralRe: Nice articlememberCarlos Saraiva Jr.8:04 21 Nov '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 21 Nov 2008
Editor: Sean Ewington
Copyright 2008 by Carlos Saraiva Jr.
Everything else Copyright © CodeProject, 1999-2009
Web17 | Advertise on the Code Project