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

简介

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

 

代码内容及下载地址

accounting.js代码如下:

View Code
/*!
* 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

formatNumber
accounting.formatNumber(5318008); // 5,318,008
accounting.formatNumber(9876543.21, 3, " "); // 9 876 543.210

unformat

unformat
accounting.unformat("£ 12,345,678.90 GBP"); // 12345678.9

 

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

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/547551.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

linux清除cpu,解决kswapd0 CPU占用率高的问题-清除病毒

连接服务器时发现cpu使用率100%&#xff0c;使用top命令查看是kswapd0进程占用cpu极高百度下后知道kswapd0进程的作用&#xff1a;它是虚拟内存管理中&#xff0c;负责换页的&#xff0c;操作系统每过一定时间就会唤醒kswapd &#xff0c;看看内存是否紧张&#xff0c;如果不紧…

Apache+Mysql+php+ZenTaoPMS安装配置文档

基于ApacheMysqlphpZenTaoPMS安装配置一、Apache安装配置tar zxvf httpd-2.2.23.tar.gzcd httpd-2.2.23mkdir –p /usr/local/app/apache2./configure --prefix/usr/local/app/apache2 --enable-so \--enable-maintainer-mode --enable-rewrite #添加后面的参数是为了解析s…

富编译器汇总及二次开发Demo

富文本编译器汇总 名称总大小当前版本官方地址扩展方法xhEditor1.43 MBv1.1.14http://xheditor.comhttp://xheditor.com/demos/demo09.htmlMarkitUp98.7 KBv1.1.13http://markitup.jaysalvat.com/home在set.js里设置开发。jwysiwyg1.52 MBv0.98https://github.com/akzhan/jwys…

docker安装nginx并配置SSL到个人博客

1 准备 1.已安装好docker环境 2.已申请好域名 2 申请SSL证书 我使用的是腾讯云&#xff0c;申请免费的TrustAsia的SSL证书&#xff0c;阿里云等或者其他平台一般都会提供TrustAsia的SSL证书的 填好域名等相关信息&#xff0c;一般一天就可以下载证书了 3 docker安装Nginx …

redhat linux 6.5 vnc,redhat 6.5 YUM安装kvm 并用VNC远程管理

安装完REDHAT&#xff0c;我们首先配置yum源先卸载系统原来的YUM包一、配置redhat yum源#rpm -aq|grep yum|xargs rpm -e --nodeps下载YUM源&#xff0c;我用的是&#xff11;&#xff16;&#xff13;的# wget http://mirrors.163.com/centos/6/os/x86_64/Packages/yum-plugin…

用DOSBox运行老游戏

DOSBox0.74-3-win32-installer.exe下载地址&#xff1a; https://nchc.dl.sourceforge.net/project/dosbox/dosbox/0.74-3/DOSBox0.74-3-win32-installer.exe 金庸群侠传&#xff1a;https://dos.zczc.cz/games/%E9%87%91%E5%BA%B8%E7%BE%A4%E4%BE%A0%E4%BC%A0/download 新版本…

宿主机为linux、windows分别实现VMware三种方式上网(转)

一、VMware三种方式工作原理1 Host-only连接方式 让虚机具有与宿主机不同的各自独立IP地址&#xff0c;但与宿主机位于不同网段&#xff0c;同时为宿主主机新增一个IP地址&#xff0c;且保证该IP地址与各虚机IP地址位于同一网段。最终结果是新建了一个由所有虚机与宿主主机所构…

摔倒、摔倒检测数据集

近期学习摔倒检测&#xff0c;接触摔倒数据集&#xff0c;自学笔记&#xff0c;仅用作个人复习。 the UR fall detection dataset (URFD)the fall detection dataset (FDD) UR Fall Detection Dataset &#xff08;University of Rzeszow - 热舒夫大学&#xff09; 数据集网…

visual studio内置“iis”组件提取及二次开发

简介 visual studio安装后会自带小型的“iis”服务器&#xff0c;本文就简单提取一下这个组件&#xff0c;自己做一个小型“iis”服务器吧。先来说用途吧&#xff08;废话可绕过&#xff09;&#xff0c;比如在服务器上没有安装iis&#xff0c;或者给客户演示asp.net程序&…

禁用 Microsoft 软件保护平台服务

以前没怎么注意&#xff0c;老觉得cup没事就声音很大&#xff0c;后来发现这玩意儿占用巨多cup&#xff0c;希望有大佬帮助解决一下&#xff0c;谢谢 解决方法&#xff1a; 首先使用【Win】 【R】组合快捷键&#xff0c;快速打开运行命令框&#xff0c;在打开后面键入命令&am…

asp.net mvc3.0安装失败之终极解决方案

安装失败截图 原因分析 因为vs10先安装了sp1补丁&#xff0c;然后安装的mvc3.0&#xff0c;某些文件被sp1补丁更改&#xff0c;导致“VS10-KB2483190-x86.exe”安装不了&#xff0c;造成安装失败。 解决方案 方法1&#xff1a; 解压mvc安装包&#xff08;AspNetMVC3Setup.e…

asp.net mvc3.0第一个程序helloworld开发图解

步骤一&#xff1a;新建asp.net mvc3.0项目 &#xff08;选择Razor模板&#xff09; 步骤二&#xff1a;创建控制器 步骤三&#xff1a;控制器源码内右键创建对应视图 步骤四&#xff1a;控制器内添加代码 步骤五&#xff1a;视图页面输出内容 步骤六&#xff1a;F5调试

在Windows系统中下载并安装Docker-desktop

在Windows系统中下载并安装Docker-desktop 推荐目录&#xff1a;https://t.cn/A6ApnczU Docker for Windows 在Windows上运行Docker。系统要求&#xff0c;Windows10x64位&#xff0c;支持Hyper-V。 下载 Docker for Windows Dokcer Desktop for Windows 安装要求 Docker …

c 语言 json序列化,C#中json字符串的序列化和反序列化 – 万能的聪哥 – 博客园...

今日写番茄闹钟程序,打算添加日程安排内容,使用到json格式文件的序列化和反序列化:什么是Json ?Json【它是一个轻量级的数据交换格式&#xff0c;我们可以很简单的来读取和写它&#xff0c;并且它很容易被计算机转化和生成&#xff0c;它是完全独立于语言的。Json支持下面两种…

PowerDesigner使用笔记

1、PowerDesigner添加字段说明 打开表设计视图>选择Columns栏目>点击“Columns and Filter”> 沟中“Comment”选项&#xff0c;随后便可添加列说明。如图&#xff1a; 2、添加表索引双击表视图进入表设计页面 > 点击Indexs栏目 > 新增一列索引 > 双击新增索…

跌倒识别 摔倒识别 -lightweight_openpose

最近做了一个跌倒检测demo&#xff0c;使用的是lightweight_openposefullconnection&#xff0c;这篇文章是以应用为主&#xff0c;已经在GitHub上开源啦&#xff0c; 源码openpose_fall_detect 为什么使用lightweight_openpose&#xff0c;在此之前跑了很多模型哈&#xff0c;…

entity framework框架生成摘要文档为空(没有元数据文档可用)的bug解决方案

简介 entity framework在vs中生成的.edmx文件&#xff0c;会导致摘要&#xff08;说明&#xff09;为空的bug&#xff0c;具体bug信息为“没有元数据文档可用。”&#xff0c;导致我们表名打点去字段时&#xff0c;无法预知字段代表的含义&#xff0c;这在开发当中也是比较致命…

ElasticSearch可视化工具Dejavu安装使用

目录 1、安装 Docker 环境2、运行 ElasticSearch 服务3、安装运行 Dejavu 服务 Dejavu 是一个 ElasticSearch 的 Web UI 工具&#xff0c;支持通过 JSON 和 CSV 文件导入数据&#xff0c;支持可视化定义 Mapping (字段映射)等。 相关描述在 https://github.com/appbaseio/dej…

介绍MFSideMenu左右滑动控件的使用

昨天刚写完侧滑菜单的实例&#xff0c;今天在CocoaChina网站上看到一篇非常好的侧滑菜单设计案例文章&#xff0c;分享给大家。http://www.cocoachina.com/macdev/uiue/2013/0716/6609.html 自从Facebook使用了左右滑动菜单导航以后&#xff0c;国内外各个App都竞相模仿该功能&…

艾诺迪亚4一次性完美刷经验刷金钱方法图解[亲测无需闪退游戏]

最近在玩游戏艾诺迪亚4&#xff0c;感觉不错就是升级太慢&#xff0c;于是研究了最新的刷等级刷金钱的方法&#xff0c;无需游戏闪退&#xff0c;一次性成功的方法&#xff0c;下面一起刷起来。 需要用的一个工具&#xff1a;八门神器&#xff08;注意&#xff1a;八门神器无需…