javascript数字格式化通用类 accounting.js使用


Posted in Javascript onAugust 24, 2012

代码内容及下载地址
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

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

三水点靠木下载地址 accounting.js

Javascript 相关文章推荐
人人网javascript面试题 可以提前实现下
Jan 05 Javascript
JS 获取浏览器和屏幕宽高等信息的实现思路及代码
Jul 31 Javascript
Node.js模块加载详解
Aug 16 Javascript
$(&quot;&quot;).click与onclick的区别示例介绍
Sep 25 Javascript
比例尺、缩略图、平移缩放之百度地图添加控件方法
Aug 03 Javascript
js实现网站最上边可关闭的浮动广告条代码
Sep 04 Javascript
利用JS制作万年历的方法
Aug 16 Javascript
在vue中,v-for的索引index在html中的使用方法
Mar 06 Javascript
详解js加减乘除精确计算
Mar 19 Javascript
详解Vue中的Props与Data细微差别
Mar 02 Javascript
vue-router 路由传参用法实例分析
Mar 06 Javascript
OpenLayers3实现地图鹰眼以及地图比例尺的添加
Sep 25 Javascript
jquery动画4.升级版遮罩效果的图片走廊--带自动运行效果
Aug 24 #Javascript
jquery动画3.创建一个带遮罩效果的图片走廊
Aug 24 #Javascript
jquery动画2.元素坐标动画效果(创建一个图片走廊)
Aug 24 #Javascript
jquery动画1.加载指示器
Aug 24 #Javascript
基于jquery的bankInput银行卡账号格式化
Aug 22 #Javascript
javascript高级程序设计第二版第十二章事件要点总结(常用的跨浏览器检测方法)
Aug 22 #Javascript
js选取多个或单个元素的实现代码(用class)
Aug 22 #Javascript
You might like
超级简单的发送邮件程序
2006/10/09 PHP
php学习笔记 [预定义数组(超全局数组)]
2011/06/09 PHP
php 多关键字 高亮显示实现代码
2012/04/23 PHP
php preg_replace替换实例讲解
2013/11/04 PHP
用php简单实现加减乘除计算器
2014/01/06 PHP
PHP JSON格式的中文显示问题解决方法
2015/04/09 PHP
PHP扩展Memcache分布式部署方案
2015/12/06 PHP
Symfony核心类概述
2016/03/17 PHP
php中array_slice和array_splice函数解析
2016/10/18 PHP
PHP中快速生成随机密码的几种方式
2017/04/17 PHP
PHP使用imagick扩展实现合并图像的方法
2017/04/25 PHP
PHP使用glob方法遍历文件夹下所有文件的实例
2018/10/17 PHP
理解javascript中的回调函数(callback)
2014/09/02 Javascript
javascript实现百度地图鼠标滑动事件显示、隐藏
2015/04/02 Javascript
jQuery在线选座位插件seat-charts特效代码分享
2015/08/27 Javascript
jQuery使用contains过滤器实现精确匹配方法详解
2016/02/25 Javascript
Nodejs中Express 常用中间件 body-parser 实现解析
2017/05/22 NodeJs
如何在vue中使用ts的示例代码
2018/02/28 Javascript
vue-cli 使用vue-bus来全局控制的实例讲解
2018/09/15 Javascript
vue使用高德地图根据坐标定位点的实现代码
2019/08/22 Javascript
基于vue+echarts 数据可视化大屏展示的方法示例
2020/03/09 Javascript
Python版微信红包分配算法
2015/05/04 Python
Python函数式编程指南(三):迭代器详解
2015/06/24 Python
python 提取文件指定列的方法示例
2019/08/07 Python
mac在matplotlib中显示中文的操作方法
2020/03/06 Python
python如何快速生成时间戳
2020/07/21 Python
python使用建议技巧分享(三)
2020/08/18 Python
为你的html5网页添加音效示例
2014/04/03 HTML / CSS
澳洲在线厨具商店:Kitchen Style
2018/05/05 全球购物
俄罗斯运动、健康和美容产品在线商店:Lactomin.ru
2020/07/23 全球购物
房屋租赁意向书
2014/04/01 职场文书
2014年工人工作总结
2014/11/25 职场文书
2014年绿化工作总结
2014/12/09 职场文书
2015个人半年总结范文
2015/03/09 职场文书
2015年英语教研组工作总结
2015/05/23 职场文书
中国现代文学之经典散文三篇
2019/09/18 职场文书