代码内容及下载地址
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:
* http://josscrowcroft.github.com/accounting.js/
*/
(function(root, undefined) {
/* --- setup --- */
// create the local library object, to be exported or referenced globally later
var lib = {};
// current version
lib.version = '0.3.2';
/* --- exposed settings --- */
// the library's settings configuration object. contains default parameters for
// currency and number formatting
lib.settings = {
currency: {
symbol : $, // default currency symbol is '$'
format : %s%v, // controls output: %s = symbol, %v = value (can be object, see docs)
decimal : ., // decimal point separator
thousand : ,, // thousands separator
precision : 2, // decimal places
grouping : 3 // digit grouping (not implemented yet)
},
number: {
precision : 0, // default precision on numbers is 0
grouping : 3, // digit grouping (not implemented yet)
thousand : ,,
decimal : .
}
};
/* --- internal helper methods --- */
// store reference to possibly-available ecmascript 5 methods for later
var nativemap = array.prototype.map,
nativeisarray = array.isarray,
tostring = object.prototype.tostring;
/**
* tests whether supplied parameter is a string
* from underscore.js
*/
function isstring(obj) {
return !!(obj === '' || (obj && obj.charcodeat && obj.substr));
}
/**
* tests whether supplied parameter is a string
* from underscore.js, delegates to ecma5's native array.isarray
*/
function isarray(obj) {
return nativeisarray ? nativeisarray(obj) : tostring.call(obj) === '[object array]';
}
/**
* tests whether supplied parameter is a true object
*/
function isobject(obj) {
return obj && tostring.call(obj) === '[object object]';
}
/**
* extends an object with a defaults object, similar to underscore's _.defaults
*
* used for abstracting parameter handling from api methods
*/
function defaults(object, defs) {
var key;
object = object || {};
defs = defs || {};
// iterate over object non-prototype properties:
for (key in defs) {
if (defs.hasownproperty(key)) {
// replace values with defaults only if undefined (allow empty/zero values):
if (object[key] == null) object[key] = defs[key];
}
}
return object;
}
/**
* implementation of `array.map()` for iteration loops
*
* returns a new array as a result of calling `iterator` on each array value.
* defers to native array.map if available
*/
function map(obj, iterator, context) {
var results = [], i, j;
if (!obj) return results;
// use native .map method if it exists:
if (nativemap && obj.map === nativemap) return obj.map(iterator, context);
// fallback for native .map:
for (i = 0, j = obj.length; i results[i] = iterator.call(context, obj[i], i, obj);
}
return results;
}
/**
* check and normalise the value of precision (must be positive integer)
*/
function checkprecision(val, base) {
val = math.round(math.abs(val));
return isnan(val)? base : val;
}
/**
* parses a format string or object and returns format obj for use in rendering
*
* `format` is either a string with the default (positive) format, or object
* containing `pos` (required), `neg` and `zero` values (or a function returning
* either a string or object)
*
* either string or format.pos must contain %v (value) to be valid
*/
function checkcurrencyformat(format) {
var defaults = lib.settings.currency.format;
// allow function as format parameter (should return string or object):
if ( typeof format === function ) format = format();
// format can be a string, in which case `value` (%v) must be present:
if ( isstring( format ) && format.match(%v) ) {
// create and return positive, negative and zero formats:
return {
pos : format,
neg : format.replace(-, ).replace(%v, -%v),
zero : format
};
// if no format, or object is missing valid positive value, use defaults:
} else if ( !format || !format.pos || !format.pos.match(%v) ) {
// if defaults is a string, casts it to an object for faster checking next time:
return ( !isstring( defaults ) ) ? defaults : lib.settings.currency.format = {
pos : defaults,
neg : defaults.replace(%v, -%v),
zero : defaults
};
}
// otherwise, assume format was fine:
return format;
}
/* --- api methods --- */
/**
* takes a string/array of strings, removes all formatting/cruft and returns the raw float value
* alias: accounting.`parse(string)`
*
* decimal must be included in the regular expression to match floats (defaults to
* accounting.settings.number.decimal), so if the number uses a non-standard decimal
* separator, provide it as the second argument.
*
* also matches bracketed negatives (eg. $ (1.99) => -1.99)
*
* doesn't throw any errors (`nan`s become 0) but this may change in future
*/
var unformat = lib.unformat = lib.parse = function(value, decimal) {
// recursively unformat arrays:
if (isarray(value)) {
return map(value, function(val) {
return unformat(val, decimal);
});
}
// fails silently (need decent errors):
value = value || 0;
// return the value as-is if it's already a number:
if (typeof value === number) return value;
// default decimal point comes from settings, but could be set to eg. , in opts:
decimal = decimal || lib.settings.number.decimal;
// build regex to strip out everything except digits, decimal point and minus sign:
var regex = new regexp([^0-9- + decimal + ], [g]),
unformatted = parsefloat(
( + value)
.replace(/\((.*)\)/, -$1) // replace bracketed values with negatives
.replace(regex, '') // strip out any cruft
.replace(decimal, '.') // make sure decimal point is standard
);
// this will fail silently which may cause trouble, let's wait and see:
return !isnan(unformatted) ? unformatted : 0;
};
/**
* implementation of tofixed() that treats floats more like decimals
*
* fixes binary rounding issues (eg. (0.615).tofixed(2) === 0.61) that present
* problems for accounting- and finance-related software.
*/
var tofixed = lib.tofixed = function(value, precision) {
precision = checkprecision(precision, lib.settings.number.precision);
var power = math.pow(10, precision);
// multiply up by precision, round accurately, then divide and use native tofixed():
return (math.round(lib.unformat(value) * power) / power).tofixed(precision);
};
/**
* format a number, with comma-separated thousands and custom precision/decimal places
*
* localise by overriding the precision and thousand / decimal separators
* 2nd parameter `precision` can be an object matching `settings.number`
*/
var formatnumber = lib.formatnumber = function(number, precision, thousand, decimal) {
// resursively format arrays:
if (isarray(number)) {
return map(number, function(val) {
return formatnumber(val, precision, thousand, decimal);
});
}
// clean up number:
number = unformat(number);
// build options object from second param (if object) or all params, extending defaults:
var opts = defaults(
(isobject(precision) ? precision : {
precision : precision,
thousand : thousand,
decimal : decimal
}),
lib.settings.number
),
// clean up precision
useprecision = checkprecision(opts.precision),
// do some calc:
negative = number base = parseint(tofixed(math.abs(number || 0), useprecision), 10) + ,
mod = base.length > 3 ? base.length % 3 : 0;
// format the number:
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] : );
};
/**
* format a number into currency
*
* usage: accounting.formatmoney(number, symbol, precision, thousandssep, decimalsep, format)
* defaults: (0, $, 2, ,, ., %s%v)
*
* localise by overriding the symbol, precision, thousand / decimal separators and format
* second param can be an object matching `settings.currency` which is the easiest way.
*
* to do: tidy up the parameters
*/
var formatmoney = lib.formatmoney = function(number, symbol, precision, thousand, decimal, format) {
// resursively format arrays:
if (isarray(number)) {
return map(number, function(val){
return formatmoney(val, symbol, precision, thousand, decimal, format);
});
}
// clean up number:
number = unformat(number);
// build options object from second param (if object) or all params, extending defaults:
var opts = defaults(
(isobject(symbol) ? symbol : {
symbol : symbol,
precision : precision,
thousand : thousand,
decimal : decimal,
format : format
}),
lib.settings.currency
),
// check format (returns object with pos, neg and zero):
formats = checkcurrencyformat(opts.format),
// choose which format to use for this value:
useformat = number > 0 ? formats.pos : number // return with currency symbol added:
return useformat.replace('%s', opts.symbol).replace('%v', formatnumber(math.abs(number), checkprecision(opts.precision), opts.thousand, opts.decimal));
};
/**
* format a list of numbers into an accounting column, padding with whitespace
* to line up currency symbols, thousand separators and decimals places
*
* list should be an array of numbers
* second parameter can be an object containing keys that match the params
*
* returns array of accouting-formatted number strings of same length
*
* nb: `white-space:pre` css rule is required on the list container to prevent
* browsers from collapsing the whitespace in the output strings.
*/
lib.formatcolumn = function(list, symbol, precision, thousand, decimal, format) {
if (!list) return [];
// build options object from second param (if object) or all params, extending defaults:
var opts = defaults(
(isobject(symbol) ? symbol : {
symbol : symbol,
precision : precision,
thousand : thousand,
decimal : decimal,
format : format
}),
lib.settings.currency
),
// check format (returns object with pos, neg and zero), only need pos for now:
formats = checkcurrencyformat(opts.format),
// whether to pad at start of string or after currency symbol:
padaftersymbol = formats.pos.indexof(%s) // store value for the length of the longest string in the column:
maxlength = 0,
// format the list according to options, store the length of the longest string:
formatted = map(list, function(val, i) {
if (isarray(val)) {
// recursively format columns if list is a multi-dimensional array:
return lib.formatcolumn(val, opts);
} else {
// clean up the value
val = unformat(val);
// choose which format to use for this value (pos, neg or zero):
var useformat = val > 0 ? formats.pos : val // format this value, push into formatted list and save the length:
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;
}
});
// pad each number in the list and send back the column of numbers:
return map(formatted, function(val, i) {
// only if this is a string (not a nested array, which would have already been padded):
if (isstring(val) && val.length // depending on symbol position, pad after symbol or at index 0:
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;
});
};
/* --- module definition --- */
// export accounting for commonjs. if being loaded as an amd module, define it as such.
// otherwise, just add `accounting` to the global object
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = lib;
}
exports.accounting = lib;
} else if (typeof define === 'function' && define.amd) {
// return the library as an amd module:
define([], function() {
return lib;
});
} else {
// use accounting.noconflict to restore `accounting` back to its original value.
// returns a reference to the library's `accounting` object;
// e.g. `var numbers = accounting.noconflict();`
lib.noconflict = (function(oldaccounting) {
return function() {
// reset the value of the root's `accounting` variable:
root.accounting = oldaccounting;
// delete the noconflict method:
lib.noconflict = undefined;
// return reference to the library to re-assign it:
return lib;
};
})(root.accounting);
// declare `fx` on the root (global/window) object:
root['accounting'] = lib;
}
// root will be `window` in browser or `global` on the server:
}(this));
官方下载地址:https://raw.github.com/josscrowcroft/accounting.js/master/accounting.js
使用实例
formatmoney
复制代码 代码如下:
formatmoney
// default usage:
accounting.formatmoney(12345678); // $12,345,678.00
// european formatting (custom symbol and separators), could also use options object as second param:
accounting.formatmoney(4999.99, ?, 2, ., ,); // ?4.999,99
// negative values are formatted nicely, too:
accounting.formatmoney(-500000, £ , 0); // £ -500,000
// simple `format` string allows control of symbol position [%v = value, %s = symbol]:
accounting.formatmoney(5318008, { symbol: gbp, format: %v %s }); // 5,318,008.00 gbp
formatnumber
复制代码 代码如下:
accounting.formatnumber(5318008); // 5,318,008
accounting.formatnumber(9876543.21, 3, ); // 9 876 543.210
unformat
复制代码 代码如下:
accounting.unformat(£ 12,345,678.90 gbp); // 12345678.9
官方演示实例:http://josscrowcroft.github.com/accounting.js/
脚本之家下载地址 accounting.js