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.

Popular posts from this blog

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

Spring Kafka - how to use ReplyingKafkaTemplate send and reply synchronously

How To Connect SSH Using PEM Certificate On Windows

Upload and Download Rest API using Spring Boot Reactive WebFlux

MIME Types - Complete List