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查詢
- Json formatJSONORM
- 求助:TypeError: unsupported format string passed to NoneType.__format__ErrorORMNone
- set excel formatExcelORM
- 問題解決:TypeError: unsupported format string passed to NoneType.__format__ErrorORMNone
- Codeforces 1974G Money Buys Less Happiness NowAPP
- Currency Assistant for Mac 貨幣兌換計算器Mac
- 如何使用 SAP CDS view 中的 currency conversion 功能View
- vim Google style formatGoORM
- [Ruby]format xml with RubyORMXML
- oracle工具 awr formatOracleORM
- mac好用的個人理財工具:Money for MacMac
- Linguistics-English-Time is money + A coin has two sides.NGUIIDE
- Spartacus Storefront 裡的 currency 和 language 的 store 設計
- jQuery Validate的format()用法jQueryORM
- 8.4.2. bytea Escape FormatORM
- JAVA中String format的用法JavaORM
- [#181024][PAT Practice] A+B FormatORM
- 針對python錯誤 format()PythonORM
- SQLITE_ERROR - table sap_capire_bookshop_books has no column named currencySQLiteErrorAPI
- 資料安全要重視!警惕“Money Message”勒索軟體!
- 12.2、python內建函式—formatPython函式ORM
- Delphi Format 格式化數字ORM
- python中zip和format的使用PythonORM
- python str.format高階用法PythonORM
- SQLSTATE [22007]: Invalid datetime format: 1292 IncorrectSQLORM
- PAT:1001 A+B Format (20分)ORM
- Conversion to Dalvik format failed: Unable to execute dexORMAI
- 連結字串String.prototype.format字串ORM
- oracle data Format Models---二(轉)OracleORM
- OAF export data from VO in xlsx formatExportORM
- libheif is an HEIF and AVIF file format decoder and encoderORM
- Clang-format格式標準化ORM
- 善用 Format 來格式化字串ORM字串
- String.format()的詳細用法ORM
- 好用的個人財務管理工具:Money Pro for macMac
- PostgreSQL DBA(116) - pgAdmin(Don't do this:Don't use money&serial)SQL
- SAP UI5 Currency 資料型別的校驗邏輯分析UI資料型別