`
c_bai
  • 浏览: 36549 次
  • 性别: Icon_minigender_1
  • 来自: 福建
社区版块
存档分类
最新评论

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

阅读更多
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));


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

    《accounting.js——轻量级财务计算库的深度解析》 在现代Web开发中,处理数字和货币计算是一项常见的任务,而accounting.js正是为此设计的一款轻量级、易用的JavaScript库。它专注于提供简单、优雅的API,用于执行...

    网页模板——vue.js实现的销售数据柱状图表统计特效源码.zip

    Vue.js是一款流行的前端JavaScript框架,它以其组件化、轻量级以及易于学习的特性,被广泛应用于构建用户界面,尤其适合单页应用程序(SPA)的开发。 【描述】:“网页模板——vue.js实现的销售数据柱状图表统计...

    网页设计与制作教程第4章 网页特效——JavaScript.ppt

    网页设计与制作教程第4章 网页特效——JavaScript.ppt网页设计与制作教程第4章 网页特效——JavaScript.ppt

    网页模板——Vue.js圆形CSS3颜色渐变色拾取器.zip

    在这个“网页模板——Vue.js圆形CSS3颜色渐变色拾取器”项目中,我们可以深入探讨Vue.js如何与CSS3技术结合,创建一个动态的颜色选择工具。 首先,Vue.js的核心在于其响应式数据绑定系统。通过使用`v-model`指令,...

    网页模板——TweenMax.js+svg实现漂亮的农场风车风景动画效果源码.zip

    2. 配置 TweenMax.js:导入库并定义要动画化的元素,设置开始和结束状态以及动画参数。 3. 使用缓动函数:选择合适的缓动函数,使动画过渡更加自然。 4. 组合动画:如果有多重动画,可以使用 Timeline 来同步和管理...

    榆落微时光v1——1.0.39.rar

    5. **数据管理**:小程序使用JSON格式的本地存储,可以保存用户数据,但容量有限。对于更大的数据需求,通常会配合后端云服务进行数据交互。 6. **发布与更新**:小程序的发布需要经过平台审核,更新时一般无需用户...

    Node.js 对比 Python:优点、缺点和用例(csdn)————程序.pdf

    Node.js 和 Python 都是流行的后端开发工具,它们各自有着独特的优点和适用场景。在决定使用哪种语言之前,需要深入了解它们的特点。 Python 以其简洁的语法和强大的库支持受到青睐,尤其在科学计算、数据分析、...

    Html——电脑病毒——特效.rar

    在本示例中,"Html——电脑病毒——特效.rar" 是一个压缩包,它包含了一个使用前端技术实现的模拟电脑病毒效果的项目。这个特效并非实际的计算机病毒,而是通过编程技巧模拟出的一种视觉效果,用于展示或教学目的。 ...

    IOS应用源码——UIWebViewBrowse.rar

    这个名为"IOS应用源码——UIWebViewBrowse.rar"的压缩包文件很可能包含了一个简单的iOS应用示例,该示例展示了如何使用UIWebView来浏览网页。让我们深入探讨一下UIWebView及其相关知识点。 **UIWebView介绍** ...

    TypeScript使用详解(csdn)————程序.pdf

    此外,TypeScript支持泛型、接口、类等面向对象的编程特性,有助于构建大型的、模块化的应用程序。 TypeScript代码在编译过程中可以进行多种配置,这些配置项保存在一个名为“tsconfig.json”的文件中。配置选项...

    JavaScript数字格式化

    该文档为javascript的数字格式化方法,可用于保留小数位,强制添0等操作

    javascript精确计算日期处理金额格式化

    Numeral.js提供了一种方便的方式来格式化数字,包括货币,百分比,数字等。例如,`numeral(1234567.89).format('0,0.00')`将输出"1,234,567.89"。accounting.js则提供了类似的功能,如`accounting.formatMoney...

    JavaScript HTML格式化 - 站长工具.htm

    JavaScript HTML格式化 - 站长工具.htm

    javascript 日期数字文本格式化

    这篇博文"javascript 日期数字文本格式化"可能详细解释了如何使用自定义工具或库来实现这一功能。 首先,我们来看`02.bizplant-util-DateFormat.js`这个文件。这很可能是一个自定义的日期格式化工具函数,可能包含...

    phoneformat.js, Javascript电话号码格式化程序.zip

    phoneformat.js, Javascript电话号码格式化程序 PhoneFormat.js 一个javascript电话格式化程序安装 Bowerbower install phoneformat.js通过 NPMnpm install phoneformat.js所有使用的文件都在/d

    finereport格式化金额函数js中进行数字超大金额千位符格式化处理.docx

    "finereport格式化金额函数js中进行数字超大金额千位符格式...finereport格式化金额函数在JS中进行数字超大金额千位符格式化处理可以使用tranNumber函数、toLocaleString()方法或slice、substr或substring方法来实现。

    Numeral.js一个用于格式化和操作数字的JavaScript库

    2. **易于使用的API**:Numeral.js提供了简洁的API,允许开发者通过`numeral(number).format(format)`来快速格式化数字。例如,`numeral(123456.789).format('0,0.00')`将返回`"123,456.79"`。 3. **数字转换**:...

    利用Google翻译实现网站国际化——js插件.rar

    【标题】:“利用Google翻译实现网站国际化——js插件” 在网页开发中,为了使网站内容能够被全球用户理解和访问,网站国际化是一个重要的步骤。这个主题涉及到如何利用Google翻译API来构建一个支持多语言的网站。...

    JavaScript代码生成器——Coffee Script.pdf

    JavaScript代码生成器——Coffee Script CoffeeScript是一种基于Ruby语言的编程语言,旨在通过简洁的编码方式生成JavaScript代码。它结合了Ruby的简洁和JavaScript的灵活性,使开发者可以通过简洁易读的语法撰写...

    JavaScript应用实例-通用型判断进度条.js

    JavaScript应用实例-通用型判断进度条.js

Global site tag (gtag.js) - Google Analytics