Format As Currency - return this value as a currency string. - Node.js String

Node.js examples for String:Format

Description

Format As Currency - return this value as a currency string.

Demo Code


/**/* ww w  .ja va2s  .  c o m*/
 * formatAsCurrency - return this value as a currency string.
 *
 * @return {String} - in currency format (e.g. '14.95')
 */
Number.prototype.formatAsCurrency = function () {
    'use strict';
    var minus = (this < 0) ? '-' : '',
        str   = String(Math.floor((Math.abs(this) + 0.005) * 100) / 100);

    if (isNaN(this) || !isFinite(this)) {
        str = '0.00';
    }

    if (str.indexOf('.') < 0) {
        str = str + '.00';
    } else if (str.indexOf('.') === (str.length - 2)) {
        str = str + '0';
    }
    return minus + str;
};

/**
 * formatAsCurrency - return this value as a currency string.
 *
 * @return {String} - in currency format (e.g. '14.95')
 */
String.prototype.formatAsCurrency = function () {
    'use strict';
    var i = parseFloat(this);
    if (isNaN(i)) {
        i = 0.00;
    }
    return i.formatAsCurrency();
};

Related Tutorials