John Smith John Smith - 7 months ago 15
Javascript Question

Format numbers as money, two decimals

How do I turn, say 1499, to 14.99? The raw numbers will always be listed as "1999", "2499", "9999" etc. with the 2 last numbers being decimals. Preferrably in jQuery.

The only code I've understood assumes that there are no decimals already, or wants to round them, similar to

var num = 10;
var result = num.toFixed(2);


The number 19999 = $199.99
The number 149 = $1.49
so two numbers from the back are decimals. Ideas? I've seen plugins that should work, but I'd prefer not having to use a plugin for this relatively small task.

Answer

I think a nice way to do this is to loop trough a string obtained from the number and just add a dot or whatever when it should be added.

function toCurrency(n) {
    var value = n.toString();
    var output = '$';
    for (var i = 0; i < value.length; ++i) {
        if (i === value.length - 2) output += '.';
        output += value[i];
    }
    return output;
}

console.log(toCurrency(2499)); // $24.99

This function could also be added as a prototype of Number like this:

Number.prototype.toCurrency = function() {
    var value = this.toString();
    var output = '$';
    for (var i = 0; i < value.length; ++i) {
        if (i === value.length - 2) output += '.';
        output += value[i];
    }
    return output;
}

var price = 12200;
price.toCurrency(); // "$122.00"

I would do it this way, but I must say that modifying primitives is not recommended