Format and un-format money/currency in JavaScript
轉自: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!
相關文章
- money查詢
- SAP 的Currency Type
- About SAP currency type
- 千份位Javascript Thousand Separator / string formatJavaScriptORM
- How to express money in EnglishExpress
- JavaScript類似c#字串處理方法format()JavaScriptC#字串ORM
- Change in Company Code Currency in SAP
- Goodbye, Money 再見,美元Go
- JavaScript & PHP模仿C#中string.format效果JavaScriptPHPC#ORM
- 函式: CONVERT_TO_LOCAL_CURRENCY函式
- Error format not a string literal and no format arguments解決方案ErrorORM
- Mysql date_format 與 Oracle to_char(date,’format’)MySqlORMOracle
- 'format' 詳解ORM
- SUN format命令ORM
- Json formatJSONORM
- set excel formatExcelORM
- 求助:TypeError: unsupported format string passed to NoneType.__format__ErrorORMNone
- mac好用的個人理財工具:Money for MacMac
- oracle工具 awr formatOracleORM
- vim Google style formatGoORM
- MYSQLDUMP TABLE IN SQL FORMATMySqlORM
- [Ruby]format xml with RubyORMXML
- 如何使用 SAP CDS view 中的 currency conversion 功能View
- Currency Assistant for Mac 貨幣兌換計算器Mac
- P1474 貨幣系統 Money Systems
- 問題解決:TypeError: unsupported format string passed to NoneType.__format__ErrorORMNone
- SQLITE_ERROR - table sap_capire_bookshop_books has no column named currencySQLiteErrorAPI
- 好用的個人財務管理工具:Money Pro for macMac
- Codeforces 1974G Money Buys Less Happiness NowAPP
- jQuery Validate的format()用法jQueryORM
- mysql DATE_FORMAT函式MySqlORM函式
- C# String.FormatC#ORM
- C# string Format示例C#ORM
- Microsoft Windows Bitmap File Format SummaryROSWindowsORM
- row header format (157)HeaderORM
- Format of Index Blocks (207)ORMIndexBloC
- How to convert a numeric value or currency to English words using C#C#
- 資料安全要重視!警惕“Money Message”勒索軟體!