javascript数字格式化通用类 accounting.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

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

我们下载地址 accounting.js

(0)

相关推荐

  • javascript清理table样式

    项目中遇到这样的需求,一大段文章正文的html代码在手机中显示不全,原因是由于其它有table,而table表格中的tr/td都携带了从word中粘贴过来的样式,需要将这一大段的字符串中的table.tr.td中携带的样式清除掉,同时还不能破坏table结构,即要保留tr中的rowspan和td中的colspan属性. html部分代码如下: <p class="MsoNormal" align="left" style="text-align:le

  • 网页上的Javascript编辑器和代码格式化

    为什么不用textarea呢? 1 没有高亮 2 tab键无法使用.--按tab键会切换到下个控件 3 没有代码格式化.--因为习惯了Eclipse的环境,可以使用ctrl+shift+F来代码进行格式化. 当然,我还没强大到自己实现的程度,而且用脚趾头都能想到肯定有人实现了,就看找不找得着. 经过了艰难的搜索,终于在SourceForge上找到一个叫EditArea的项目,感觉挺好.http://sourceforge.net/projects/editarea/ 它的sample也很清楚 在

  • 用JavaScript将从数据库中读取出来的日期型格式化为想要的类型。

    复制代码 代码如下: //传入从数据库中取出的日期类型数据 function getformatdate(d){ var formate_datetime; var array = d.split(" "); var date = array[0]; var time = array[1]; var array_date = date.split("-"); var array_time = time.split(":"); var second

  • JavaScript格式化日期时间的方法和自定义格式化函数示例

    很多时候,我们可以利用JavaScript中Date对象的内置方法来格式化,如: 复制代码 代码如下: var d = new Date();console.log(d); // 输出:Mon Nov 04 2013 21:50:33 GMT+0800 (中国标准时间)console.log(d.toDateString()); // 日期字符串,输出:Mon Nov 04 2013console.log(d.toGMTString()); // 格林威治时间,输出:Mon, 04 Nov 20

  • javascript格式化日期时间函数

    复制代码 代码如下: function DateUtil(){}/***功能:格式化时间*示例:DateUtil.Format("yyyy/MM/dd","Thu Nov 9 20:30:37 UTC+0800 2006 ");*返回:2006/11/09*/DateUtil.Format=function(fmtCode,date){    var result,d,arr_d;        var patrn_now_1=/^y{4}-M{2}-d{2}\sh

  • javascript 清除输入框中的数据

    <li id=""><span>***</span>评论<span>鲜果</span><a href="#message_area" onclick=" fillInMessageArea(this);">回复</a></li> <li id=""><span>pizicai</span>评论&l

  • javascript数字格式化通用类 accounting.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 documenta

  • javascript 数字格式化输出的实现代码

    复制代码 代码如下: <script type="text/javascript">var format = function (number, form) {    var forms = form.split('.'), number = '' + number, numbers = number.split('.')        , leftnumber = numbers[0].split('')        , exec = function (lastMat

  • JS实现的数字格式化功能示例

    本文实例讲述了JS实现的数字格式化功能.分享给大家供大家参考,具体如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head&g

  • 5个javascript的数字格式化函数分享

    十进制四舍五入 这两段代码帮助你做到四舍五入,对于你显示价格或者订单比较有用: 代码1: 复制代码 代码如下: function CurrencyFormatted(amount) { var i = parseFloat(amount); if(isNaN(i)) { i = 0.00; } var minus = ''; if(i < 0) { minus = '-'; } i = Math.abs(i); i = parseInt((i + .005) * 100); i = i / 10

  • JavaScript中使用toLocaleString数字格式化处理详解

    目录 toLocaleString 偷懒小帮手啊~ Number.prototype.toLocaleString() 1. 数字分割成千分位 2. 保留几位小数 3. 使用的整数数字的最小数目minimumIntegerDigits 4. 使用的有效数字的最小数目minimumSignificantDigits 5. 使用的有效数字的最大数目maximumSignificantDigits 6. 展示的样式style toLocaleString 偷懒小帮手啊~ 项目中给数字做格式化处理的问题

  • 详解JavaScript时间格式化

    感谢某前辈写的JS格式化日期和时间JS代码,很好很强大!!! 前言: js虽然提供了各种获取时间Date对象的不同属性方法,如:getDate 方法 | getDay 方法 | getFullYear 方法 | getHours 方法 ... ... 等等,但是却没有像java那样提供一个方法来供用户来根据自身提供的模板(pattern),来格式化指定时间对象,所以自己就封装了一个小方法,只供大家闲来调侃-.-,有好的建议还望慷慨指荐哦. 用到知识点: • arguments:该对象代表正在执行

  • 在JavaScript中调用Java类和接口的方法

    前言 本文中所有的代码使用 JavaScript 编写,但你也可以用其他兼容 JSR 223 的脚本语言.这些例子可作为脚本文件也可以在交互式 Shell 中一次运行一个语句的方式来运行.在 JavaScript 中访问对象的属性和方法的语法与 Java 语言相同. 本文包含如下几部分: 1.访问 Java 类 为了在 JavaScript 中访问原生类型或者引用 Java 类型,可以调用 Java.type() 函数,该函数根据传入的完整类名返回对应对象的类型.下面代码显示如何获取不同的对象类

  • Asp.Net类型转换类(通用类)代码分享

    废话不多说了,直接给大家贴代码了,具体代码如下所述: /// <summary> /// 类型转换类 /// 处理数据库获取字段为空的情况 /// </summary> public static class DBConvert { #region------------------ToInt32类型转换------------------ /// <summary> /// 读取数据库中字符串并转换成Int32 /// 为空时返回0 /// </summary&

  • Javascript日期格式化format函数的使用方法

    前言 Javascript日期格式化在日常开发中还是挺常见的,那么下面就给大家分享Javascript时间格式format函数的两种使用方法示例,一起来看看. 方法一 Date.prototype.pattern=function(fmt) { var o = { "M+" : this.getMonth()+1, //月份 "d+" : this.getDate(), //日 "h+" : this.getHours()%12 == 0 ? 1

  • 解决JavaScript数字精度丢失问题的方法

    本文分为三个部分 JS 数字精度丢失的一些典型问题 JS 数字精度丢失的原因 解决方案(一个对象+一个函数) 一.JS数字精度丢失的一些典型问题 1. 两个简单的浮点数相加 0.1 + 0.2 != 0.3 // true 这真不是 Firebug 的问题,可以用alert试试 (哈哈开玩笑). 看看Java的运算结果 再看看Python 2. 大整数运算 16位和17位数竟然相等,没天理啊. 又如 var x = 9007199254740992 x + 1 == x // ? 看结果 三观又

随机推荐