• Breaking News

    Easy and simple format numbers as currency string in JavaScript

    Yeah, I know, you want to format a price in JavaScript and you would like a function which takes a float as an argument and returns a string formatted like this:

    U$S 2,700.25

    Or maybe, like this:

    AR$ 2.700,25

    What's the best way to do this?

    A simple approach

    Even when JavaScript has a number formatter and it's part of the Internationalization API not all browsers support it.

    This approach meets the following criteria:

    • Does not depend on an external dependency.
    • Does support localization.
    • Does have tests/proofs.
    • Does use simple and best coding practices (no complicated regex's, uses standard coding patterns).

    The code

    (function(exports) {
    
        exports.print = function(nStr, sTho, sDec, nSign) {
            nStr += '';
            var x = nStr.split(sDec);
            var x1 = x[0];
            var x2 = x.length > 1 ? sDec + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + sTho + '$2');
            }
            var res = x2.split(sDec);
            if (res.length == 1) {
                x2 = sDec + '00';
                return nSign + x1 + x2;
            }
            if (res[1].length < 2) {
                x2 = x2 + '0';
                return nSign + x1 + x2.substring(0, 3);
            } else {
                return nSign + x1 + x2.substring(0, 3);
            }
        }
    
    })(typeof exports === 'undefined' ? this.currencyFormat = {} : exports);

    How does it work?

    This JavaScript function called currencyFormat.print() will receive #4 parameters:

    nStr = (String) A string that represents the number to be printed in currency format as result.
    sTho = (Char) Thousand character separator.
    sDec = (Char) Decimal character separator.
    nSym = (String) The currency symbol.

    As result, a  final formatted String will be returned.

    Example

    Let's suppose you receive from your backend the number "123.99" and you want to print it in dollar currency, then you call the function currencyFormat.print() as: 

    currencyFormat.print('123.99',',','.','u$s ');
    By default, the function will return 2 decimals.

    Tested with inputs

    Got these results:

    currencyFormat.print('120',',','.','U$S ');        //  U$S 120.00 
    currencyFormat.print('120.2',',','.','U$S ');      // U$S 120.20 
    currencyFormat.print('-1230.99',',','.','U$S ')    // U$S -1,230.99  
    currencyFormat.print('120','.',',','AR$ ')         // AR$ 120,00  
    currencyFormat.print('120,2','.',',','AR$ ')       // AR$ 120,20  
    currencyFormat.print('12000',',','.','U$S ')       // U$S 12,000.00  
    currencyFormat.print('12000.232',',','.','U$S ')   // U$S 12,000.23  
    currencyFormat.print('2312000.232',',','.','U$S ') // U$S 2,312,000.23  
    currencyFormat.print('2312000,232','.',',','AR$ ') // AR$ 2.312.000,23;

    If you found this JavaScript function useful then feel free to use it at your convenience.

    No comments