a blog by Christian Snodgrass
about programming, web and game design, and everything else

Quick Tip: Adding Commas to Numbers

A common problem that you may run into when you want to output a number is to add commas. It’s much easier to understand 1,000,000 than it is to read 1000000.

I haven’t done this in a while so I did a quick search to see what others were doing to tackle this problem. A lot of the solutions I found seemed to be a bit overzealous and excessive.

So, I created my own little function, which I thought I’d share. Since I do articles for ActionScript 3, Javascript, and PHP, I figured I’d give it to you in all three.

The Code

The code is nearly identical between ActionScript 3 and Javascript. PHP is a bit different, but all the same ideas.

ActionScript 3

public function AddCommas(val:Number):String { 
    var valStr:String = val.toString(); 
    var parts:Vector. = new Vector.(); 
     
    while(valStr > (valStr.substr(0, 1)=="-" ? 1 : 0)) { 
        parts.splice(0, 0, valStr.substr(-3)); 
        valStr = valStr.substr(0, valStr.length - 3); 
     
    return valStr + parts.join(','); 

Javascript

function AddCommas(val) { 
    var valStr = val.toString(); 
    var parts = []; 
 
    while(valStr > (valStr.substr(0, 1) == "-" ? 1 : 0)) { 
        parts.splice(0, 0, valStr.substr(-3)); 
        valStr = valStr.substr(0, valStr.length - 3); 
 
    return valStr + parts.join(','); 

PHP

function AddCommas($val) { 
    $val = (string)$val; 
    $parts = array(); 
 
    while($val > (substr($val, 0, 1) == '-' ? 1 : 0)) { 
        array_splice($parts, 0, 0, $val.substr(-3)); 
        $val = substr($val, 0, -3); 
 
    return $val . implode(',', $parts); 

How it Works

This is a pretty simple solution. Here is what we do, step-by-step:

And that’s it! Short, sweet, and simple.

I didn’t have any need for decimal handling, but you could easily add that. Before the loop, simply check for an index of a decimal, then remove that and everything beyond it from the string and put at at the end of the array.

You could also internationalize this function by making it so you can pass an optional separator variable (some countries switch the roles of comma and decimal in numbers, so they may have 1.234,56 instead of 1,234.56).


Related Articles


Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Back to Top