只要做過報表、電商或任何跟金額有關的畫面,就會遇到同一批需求:千分位逗號、固定小數位、貨幣符號、負數怎麼顯示、還要能反過來把「$12,345,678.90」還原成數字。accounting.js 就是把這些瑣事一次處理掉的輕量函式庫,採 MIT 授權,作者為 Joss Crowcroft。
整個庫的行為由 lib.settings 控制,分 currency 與 number 兩組。currency 組包含 symbol(預設 "$")、format(預設 "%s%v",%s 是符號、%v 是數值)、decimal、thousand、precision 與 grouping;number 組則是 precision、thousand、decimal 等。要全域調整樣式,改這裡即可,不必每次呼叫都帶一堆參數。
unformat/parse:把帶格式的字串還原成數字,會自動處理括號負數(例如 "$ (1.99)" 轉為 -1.99),非數字部分一律剝除,無法解析時回傳 0 而不丟錯。
toFixed:實作一個「更像十進位」的 toFixed,繞開 (0.615).toFixed(2) 得到 "0.61" 這類二進位浮點誤差——這對財務計算而言是致命等級的問題。
formatNumber:加上千分位與指定小數位。
formatMoney:在數字前加上貨幣符號,並依正負零套用不同格式。
formatColumn:把一整欄數字對齊,讓符號、千分位與小數點都排整齊(使用時容器需設 white-space:pre,否則空白會被瀏覽器摺掉)。
accounting.formatMoney(12345678); // $12,345,678.00
// 歐洲式格式:自訂符號與分隔符號,第二個參數也可以傳物件
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
// 負數也能漂亮呈現
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000
// 用 format 字串控制符號位置
accounting.formatMoney(5318008, { symbol: "GBP", format: "%v %s" }); // 5,318,008.00 GBP
accounting.formatNumber(5318008); // 5,318,008
accounting.formatNumber(9876543.21, 3, " "); // 9 876 543.210
accounting.unformat("£ 12,345,678.90 GBP"); // 12345678.9
檔案尾端同時照顧了三種載入環境:CommonJS(module.exports)、AMD(define)以及瀏覽器全域(掛在 root 上),並提供 noConflict 讓既有專案把 accounting 這個名稱還回去。內部大量借用了 underscore.js 的 isString、isArray 概念,並在可能的情況下優先使用 ECMAScript 5 的原生 map 與 Array.isArray。
官方下載:
https://raw.github.com/josscrowcroft/accounting.js/master/accounting.js
官方展示頁:
https://josscrowcroft.github.com/accounting.js/
程式碼內容如下:
/*!
* accounting.js v0.3.2
* Copyright 2011, Joss Crowcroft
*
* Freely distributable under the MIT license.
* Portions of accounting.js are inspired or borrowed from underscore.js
*
* Full details and documentation:
* https://josscrowcroft.github.com/accounting.js/
*/
(function(root, undefined) {
var lib = {};
lib.version = '0.3.2';
lib.settings = {
currency: {
symbol : "$",
format : "%s%v",
decimal : ".",
thousand : ",",
precision : 2,
grouping : 3
},
number: {
precision : 0,
grouping : 3,
thousand : ",",
decimal : "."
}
};
var nativeMap = Array.prototype.map,
nativeIsArray = Array.isArray,
toString = Object.prototype.toString;
function isString(obj) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
}
function isArray(obj) {
return nativeIsArray ? nativeIsArray(obj) : toString.call(obj) === '[object Array]';
}
function isObject(obj) {
return obj && toString.call(obj) === '[object Object]';
}
function defaults(object, defs) {
var key;
object = object || {};
defs = defs || {};
for (key in defs) {
if (defs.hasOwnProperty(key)) {
if (object[key] == null) object[key] = defs[key];
}
}
return object;
}
function map(obj, iterator, context) {
var results = [], i, j;
if (!obj) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
for (i = 0, j = obj.length; i < j; i++ ) {
results[i] = iterator.call(context, obj[i], i, obj);
}
return results;
}
function checkPrecision(val, base) {
val = Math.round(Math.abs(val));
return isNaN(val)? base : val;
}
function checkCurrencyFormat(format) {
var defaults = lib.settings.currency.format;
if ( typeof format === "function" ) format = format();
if ( isString( format ) && format.match("%v") ) {
return {
pos : format,
neg : format.replace("-", "").replace("%v", "-%v"),
zero : format
};
} else if ( !format || !format.pos || !format.pos.match("%v") ) {
return ( !isString( defaults ) ) ? defaults : lib.settings.currency.format = {
pos : defaults,
neg : defaults.replace("%v", "-%v"),
zero : defaults
};
}
return format;
}
var unformat = lib.unformat = lib.parse = function(value, decimal) {
if (isArray(value)) {
return map(value, function(val) {
return unformat(val, decimal);
});
}
value = value || 0;
if (typeof value === "number") return value;
decimal = decimal || lib.settings.number.decimal;
var regex = new RegExp("[^0-9-" + decimal + "]", ["g"]),
unformatted = parseFloat(
("" + value)
.replace(/\((.*)\)/, "-$1")
.replace(regex, '')
.replace(decimal, '.')
);
return !isNaN(unformatted) ? unformatted : 0;
};
var toFixed = lib.toFixed = function(value, precision) {
precision = checkPrecision(precision, lib.settings.number.precision);
var power = Math.pow(10, precision);
return (Math.round(lib.unformat(value) * power) / power).toFixed(precision);
};
var formatNumber = lib.formatNumber = function(number, precision, thousand, decimal) {
if (isArray(number)) {
return map(number, function(val) {
return formatNumber(val, precision, thousand, decimal);
});
}
number = unformat(number);
var opts = defaults(
(isObject(precision) ? precision : {
precision : precision,
thousand : thousand,
decimal : decimal
}),
lib.settings.number
),
usePrecision = checkPrecision(opts.precision),
negative = number < 0 ? "-" : "",
base = parseInt(toFixed(Math.abs(number || 0), usePrecision), 10) + "",
mod = base.length > 3 ? base.length % 3 : 0;
return negative + (mod ? base.substr(0, mod) + opts.thousand : "") + base.substr(mod).replace(/(\d{3})(?=\d)/g, "$1" + opts.thousand) + (usePrecision ? opts.decimal + toFixed(Math.abs(number), usePrecision).split('.')[1] : "");
};
var formatMoney = lib.formatMoney = function(number, symbol, precision, thousand, decimal, format) {
if (isArray(number)) {
return map(number, function(val){
return formatMoney(val, symbol, precision, thousand, decimal, format);
});
}
number = unformat(number);
var opts = defaults(
(isObject(symbol) ? symbol : {
symbol : symbol,
precision : precision,
thousand : thousand,
decimal : decimal,
format : format
}),
lib.settings.currency
),
formats = checkCurrencyFormat(opts.format),
useFormat = number > 0 ? formats.pos : number < 0 ? formats.neg : formats.zero;
return useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts.precision), opts.thousand, opts.decimal));
};
lib.formatColumn = function(list, symbol, precision, thousand, decimal, format) {
if (!list) return [];
var opts = defaults(
(isObject(symbol) ? symbol : {
symbol : symbol,
precision : precision,
thousand : thousand,
decimal : decimal,
format : format
}),
lib.settings.currency
),
formats = checkCurrencyFormat(opts.format),
padAfterSymbol = formats.pos.indexOf("%s") < formats.pos.indexOf("%v") ? true : false,
maxLength = 0,
formatted = map(list, function(val, i) {
if (isArray(val)) {
return lib.formatColumn(val, opts);
} else {
val = unformat(val);
var useFormat = val > 0 ? formats.pos : val < 0 ? formats.neg : formats.zero,
fVal = useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(val), checkPrecision(opts.precision), opts.thousand, opts.decimal));
if (fVal.length > maxLength) maxLength = fVal.length;
return fVal;
}
});
return map(formatted, function(val, i) {
if (isString(val) && val.length < maxLength) {
return padAfterSymbol ? val.replace(opts.symbol, opts.symbol+(new Array(maxLength - val.length + 1).join(" "))) : (new Array(maxLength - val.length + 1).join(" ")) + val;
}
return val;
});
};
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = lib;
}
exports.accounting = lib;
} else if (typeof define === 'function' && define.amd) {
define([], function() {
return lib;
});
} else {
lib.noConflict = (function(oldAccounting) {
return function() {
root.accounting = oldAccounting;
lib.noConflict = undefined;
return lib;
};
})(root.accounting);
root['accounting'] = lib;
}
}(this));