Format and un-format money/currency in JavaScript

weixin_34320159發表於2018-06-08

轉自:http://www.josscrowcroft.com/2011/code/format-unformat-money-currency-javascript/

Here’s a couple of simple JavaScript money-formattin’ snippets I use all the time where currencies are handled.

The code in this post has been expanded intoaccounting.js, a tiny JS library with some handy methods for number, money and currency formatting. Check it out!

Also: need to do real-time currency conversion in your apps and sites? Take a look at theOpen Exchange RatesAPI!

The first is a function to format money/currency in JavaScript, turning an integer or float into a formatted string (with customisable decimal precision, currency symbol, decimal- and thousands-separators).

The second is a regular expression that removes currency formatting, so thatparseInt/parseFloatcan be used to extract the value from a currency-formatted string.

JavaScript Money Format

This extends the native Number object, so that all new numbers (integers/floats) can have themoneyformat()method called on them. If you prefer not to extend JavaScript’s native Number object for any reason, this also works fine as a standalone function or a library method (examples below.)

// Extend the default Number object with a formatMoney() method:

// usage: someVar.formatMoney(decimalPlaces, symbol, thousandsSeparator, decimalSeparator)

// defaults: (2, "$", ",", ".")

Number.prototype.formatMoney = function(places, symbol, thousand, decimal) {

places = !isNaN(places = Math.abs(places)) ? places : 2;

symbol = symbol !== undefined ? symbol : "$";

thousand = thousand || ",";

decimal = decimal || ".";

var number = this,

    negative = number < 0 ? "-" : "",

    i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",

    j = (j = i.length) > 3 ? j % 3 : 0;

return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");

};

NB: minified version below.

Some JS currency-formatting examples:

// Default usage and custom precision/symbol :

var revenue = 12345678;

console.log(revenue.formatMoney()); // $12,345,678.00

console.log(revenue.formatMoney(0, "HK$ ")); // HK$ 12,345,678

// European formatting:

var price = 4999.99;

console.log(price.formatMoney(2, "€", ".", ",")); // €4.999,99

// It works for negative values, too:

console.log( (-500000).formatMoney(0, "£ ") ); // £ -500,000

Currency to number – removing money formatting:

Say you have a currency-formatted string, eg."HK$ -100,000.50"and you want to get the value from that, removing all currency formatting andthousand-separators. Default methods won’t get you very far:parseIntandparseFloatboth returnNaN(“not a number”, as the string had non-numeric characters in it.)

No problemo. A simpleregexwill take care of this:

var price = (12345.99).formatMoney(); // "$12,345.99"

// Remove non-numeric chars (except decimal point/minus sign):

priceVal = parseFloat(price.replace(/[^0-9-.]/g, '')); // 12345.99

NB: This only works where the decimal separator is a point (.) – if the separator is a comma (,), put a comma in the regex instead of a point, eg:/[^0-9-,]/g

Hope somebody finds this useful!

Non-Number.prototype version:

// To set it up as a global function:

function formatMoney(number, places, symbol, thousand, decimal) {

number = number || 0;

places = !isNaN(places = Math.abs(places)) ? places : 2;

symbol = symbol !== undefined ? symbol : "$";

thousand = thousand || ",";

decimal = decimal || ".";

var negative = number < 0 ? "-" : "",

    i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",

    j = (j = i.length) > 3 ? j % 3 : 0;

return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");

}

// To create it as a library method:

myLibrary.formatMoney = function(number, places, symbol, thousand, decimal) {

/* as above */

}

// Example usage:

formatMoney(54321); // $54,321

myLibrary.formatMoney(12345, 0, "£ "); // £ 12,345

Minified version of prototype method

Number.prototype.formatMoney=function(d,g,h,a){d=!isNaN(d=Math.abs(d))?d:2;g=g!==undefined?g:"$";h=h||",";a=a||".";var f=this,c=f3?b%3:0;return g+c+(b?e.substr(0,b)+h:"")+e.substr(b).replace(/(\d{3})(?=\d)/g,"$1"+h)+(d?a+Math.abs(f-e).toFixed(d).slice(2):"");};

Have any improvements, or spot any bugs? Comments appreciated! 

相關文章