简介

accounting.js 是一个非常小的JavaScript方法库用于对数字,金额和货币进行格式化。并提供可选的Excel风格列渲染。它没有依赖任何JS框架。货币符号等可以按需求进行定制。

代码内容及下载地址

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 < j; 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 < 0 ? "-" : "",
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 < 0 ? formats.neg : formats.zero; // 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") < formats.pos.indexOf("%v") ? true : false, // 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 < 0 ? formats.neg : formats.zero, // 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 < maxLength) {
// 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

//尝试demo

//工具 accounting.js
/*!
* accounting.js v0.4.1
* Copyright 2014 Open Exchange Rates
*
* Freely distributable under the MIT license.
* Portions of accounting.js are inspired or borrowed from underscore.js
*
* Full details and documentation:
* http://openexchangerates.github.io/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.4.1'; /* --- 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 < j; 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
* Alias: `accounting.format()`
*
* Localise by overriding the precision and thousand / decimal separators
* 2nd parameter `precision` can be an object matching `settings.number`
*/
var formatNumber = lib.formatNumber = lib.format = 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 < 0 ? "-" : "",
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 < 0 ? formats.neg : formats.zero; // 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") < formats.pos.indexOf("%v") ? true : false, // 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 < 0 ? formats.neg : formats.zero, // 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 < maxLength) {
// 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)); //自己代码
let util = new Object(); /**
* @description 金额格式化
* @param money 要格式化的金额
* @param config 金额格式化配置对象,默认值为{moneySymbol: '', decimalPlaces: 2, thousandsSeparator: ',', decimalSeparator: '.', format: '%s%v'}
* moneySymbol:格式化符号;decimalPlaces:小数位数;thousandsSeparator:千分位分隔符;decimalSeparator:小数位分隔符;format:控制符号位置,%v为值,%s为符号,默认为%s%v
*/
util.formatMoney = (money, config) => {
config = Object.assign({moneySymbol: '', decimalPlaces: 2, thousandsSeparator: ',', decimalSeparator: '.', format: '%v%s'}, config);
return accounting.formatMoney(money, config.moneySymbol, config.decimalPlaces, config.thousandsSeparator, config.decimalSeparator, config.format,);
}; console.log( util.formatMoney('4852100', {moneySymbol: '¥', decimalPlaces: 2, thousandsSeparator: ',', decimalSeparator: '.', format: '%v%s'}) ); //"4,852,100.00¥" console.log( util.formatMoney('4852100', {moneySymbol: '¥ ', decimalPlaces: 2, thousandsSeparator: ',', decimalSeparator: '.', format: '%s%v'}) ); //"¥ 4,852,100.00"

演示地址:https://codepen.io/namePeach/pen/agwNVw?editors=0012

官方演示实例:http://josscrowcroft.github.com/accounting.js/

                         http://openexchangerates.github.io/accounting.js/

转载:https://www.cnblogs.com/vipstone/archive/2012/08/24/2653871.html

javascript数字格式化通用类——accounting.js使用的更多相关文章

  1. javascript 数字格式化

    对数字进行格式化输出,是非常有意义的一件事情,例如许多时候,我们希望一个数字能够输出为指定格式的字符串,拿25.9878来说,我们可能会希望它能保留两位小数来说出,即结果为25.99,或者对于0.34 ...

  2. 5个缺失的 JavaScript 数字格式化函数

    /** 下面两个函数都能对浮点数进行四舍五入,保留小数点后两位 **/ function CurrencyFormatted(amount) { var i = parseFloat(amount); ...

  3. Java学习笔记 06 数字格式化及数学运算

    一.数字格式化 DecimalFormat类 >>DecimalFormat是NumberFormat的子类,用于格式化十进制数,可以将一些数字格式化为整数.浮点数.百分数等.通过使用该类 ...

  4. JavaScript 系列--JavaScript一些奇淫技巧的实现方法(二)数字格式化 1234567890转1,234,567,890;argruments 对象(类数组)转换成数组

    一.前言 之前写了一篇文章:JavaScript 系列--JavaScript一些奇淫技巧的实现方法(一)简短的sleep函数,获取时间戳 https://www.mwcxs.top/page/746 ...

  5. JavaScript 数字滚动countup.js

    1. 概述 1.1 说明 在项目过程中,有时候需要动态的去展示一些数据的加载状态,如一个数字为10000,需要5秒时间滚动加载完成.此时使用countup.js就能够很方便的处理此类功能问题. 1.2 ...

  6. js 金融数字格式化

    js 金融数字格式化 finance money number format 数字格式化 regex `123456789`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') ...

  7. sublime格式化js、css、html的通用插件-html js css pretty

    sublime格式化js.css.html的通用插件-html js css pretty: 这个插件可以格式化基本上所有js html css文件,包括写在html中的js代码 ,可以在packag ...

  8. Java基础(三十五)Math、Random类和数字格式化(String.format方法)

    一.Math类 Math类常用的方法: public static long abs (double a) 返回a的绝对值 public static double max (double a,dou ...

  9. 数字格式化的 js 库

    数字格式化的 js 库 Numeral.js,是一个用于格式化数字和处理数字的 js 库. Tip:目前 Star 有 9.2k,5年以前就没有在更新.其文档写得不很清晰,比如它提供了多语言,但如何切 ...

随机推荐

  1. Hype-v创建服务器实例

    1.创建虚拟交换机,如下图所示(虚拟交换机,只需要创建一次,后面增加服务器实例的时候,只需要选择这个虚拟交换机就可以了,不用每次都创建) 2.服务器主网络共享给虚拟交换机,如下图所 3.虚拟交换机的I ...

  2. Airbnb新用户的民宿预定结果预测

    1. 背景 关于这个数据集,在这个挑战中,您将获得一个用户列表以及他们的人口统计数据.web会话记录和一些汇总统计信息.您被要求预测新用户的第一个预订目的地将是哪个国家.这个数据集中的所有用户都来自美 ...

  3. 关于IC电源管脚去耦电容

    原文地址:https://mp.weixin.qq.com/s/0dAyTpAcQWXlYULqCeKgFA 每个集成电路(IC)都必须使用电容将各电源引脚连接到器件上的地,原因有二:防止噪声影响其本 ...

  4. Swift 基本语法

    如果创建的是 OS X playground 需要引入 Cocoa : import Cocoa /* 我的第一个 Swift 程序 */ var myString = "Hello, Wo ...

  5. ubuntu18 faster-rcnn

    luo@luo-All-Series:~/MyFile$ luo@luo-All-Series:~/MyFile$ luo@luo-All-Series:~/MyFile$ git clone htt ...

  6. Python xlwt 模块执行出错Exception: String longer than 32767 characters

    使用Python搜集数据时用到xlwt保存到excel文件,但是数据量有点大时出现 Exception: String longer than 32767 characters 搜索类似的问题都是建议 ...

  7. Pedro domingos

    Dear Professor:           I am a university student in China and study on MLN recently;             ...

  8. 启动页面、icon图标设置

    更多尺寸像素如何放置请看:http://chicun.jammy.cc/ 如何设置App的启动图,也就是Launch Image? 新建一个iosLaunchImage文件夹

  9. ansible实践

    ansible常用module ansible-doc -l List available modules -s Show playbook snippet for specified module( ...

  10. unity3d 触屏多点触控(旋转与缩放)

    unity3d 触屏多点触控(旋转与缩放) /*Touch OrbitProgrammed by: Randal J. Phillips (Caliber Mengsk)Original Creati ...