Sunday, June 3, 2012

Handy Number Formatting Function for JavaScript

If you ever had the experience of writing JavaScript, needing a simple function to quickly format a number but weren't interested in importing an entire library just for one small use, I may have an answer for you.  While working on a side project, I wrote this:


function formatNumber(rawNumber){
    var sourceString = rawNumber.toString();
    var sourceStringLength = sourceString.length;
    var targetString = '';
    var charCounter = 1;
   
    for(var i = sourceStringLength; i >= 0; i--){
        if(charCounter == 3){
            targetString = ',' + sourceString.charAt(i-1) + targetString;
            charCounter = 1;
        }
        else{
            targetString = sourceString.charAt(i-1) + targetString;
            charCounter++;
        }
    }
   
    if(targetString.charAt(0) == ","){
        targetString = targetString.substring(1,targetString.length);
    }
    alert("the final answer is " + targetString);
}


formatNumber(12345678);

Please feel free to comment and suggest changes.  From the testing I've done, it appears to work rather nicely.

No comments:

Post a Comment