views:

229

answers:

1

Much like the Stackoverlow reputation rounding, I'm hoping to do the same thing with currency

$1,000 => 1k

$1,000,000 => 1m

Is there a library out there already that does this? (preferably in jQuery)

+7  A: 

Here is a simple function to do it:

function abbrNum(number, decPlaces) {
    // 2 decimal places => 100, 3 => 1000, etc
    decPlaces = Math.pow(10,decPlaces);

    // Enumerate number abbreviations
    var abbrev = [ "k", "m", "b", "t" ];

    // Go through the array backwards, so we do the largest first
    for (var i=abbrev.length-1; i>=0; i--) {

        // Convert array index to "1000", "1000000", etc
        var size = Math.pow(10,(i+1)*3);

        // If the number is bigger or equal do the abbreviation
        if(size <= number) {
             // Here, we multiply by decPlaces, round, and then divide by decPlaces.
             // This gives us nice rounding to a particular decimal place.
             number = Math.round(number*decPlaces/size)/decPlaces;

             // Add the letter for the abbreviation
             number += abbrev[i];

             // We are done... stop
             break;
        }
    }

    return number;
}

Outputs:

abbrNum(12 , 1)          => 12
abbrNum(0 , 2)           => 0
abbrNum(1234 , 0)        => 1k
abbrNum(34567 , 2)       => 34.57k
abbrNum(918395 , 1)      => 918.4k
abbrNum(2134124 , 2)     => 2.13m
abbrNum(47475782130 , 2) => 47.48b
Jeff B
this feels golfy. how small can we get this function?
David Murdoch
lol, much smaller I am sure.
Jeff B
FUND IT.Seriously though, I'd love to see that in a golf thread.
Damien Wilson
@Jeff B: Thank you! This is a great start -- I didn't expect anyone to actually write me a function!
Baloneysammitch
@ Damien Wilson: Code-golf tag added. What do you mean by fund?
Baloneysammitch
@Baloney: I was just making it flexible. Do what is best for your application. An "appropriate cut-off" point is often subjective and/or application specific.
Jeff B
Code golf version posted [here](http://stackoverflow.com/questions/2692323/code-golf-number-formatter). For contributing members of OP question: feel free to change the parameters of the question...I had a difficult time deciding the limitations/boundaries.
David Murdoch
`function a(n,d){x=(''+n).length,p=Math.pow,d=p(10,d);x-=x%3;return Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3]}` --- Sufficiently Golfed (108)? :)
gnarf