JS Format Money Examples

Javascript  Logo Yellow

Javascript don't have money formatting, while in fact almost all top languages don't have that kind of feature, even though this format is largely used in business software. Here's what i a usually use to do money formatting.

Number.prototype.format = function(n, x, s, c) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
        num = this.toFixed(Math.max(0, ~~n));
    return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
};

To use it simply look at these examples:

(123000000).format(0, 3, ".", ","); //"123.000.000"
(123000000).format(0, 3, ",", "."); //"123,000,000"
(123000000).format(2, 3, ",", "."); //"123,000,000.00"
(123000000.99).format(2, 3, ",", "."); // "123,000,000.99"

Problem with money format is that while money is usually a number, you can do mathematical operation like adding, subtracting, etc. But once it has been formatted into money, it will become string, so it can be calculated using mathematical operator anymore. Also each different country has different format, so it's kind of not easy thing to do.

Comments

Popular posts from this blog

How To Uninstall Angular CLI, The Angular Framework

ERROR 1348 Column Password Is Not Updatable When Updating MySQL Root Password

Is Nox Player a Malware? Nox Android Emulator

ASUS Battery Health Charging Software To Make Your Battery Life Longer

How To Create Spring Boot Project Using Netbeans