jquery formatCurrency货币格式化处理

//  This file is part of the jQuery formatCurrency Plugin.
//
//    The jQuery formatCurrency Plugin is free software: you can redistribute it
//    and/or modify it under the terms of the GNU General Public License as published
//    by the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.

//    The jQuery formatCurrency Plugin is distributed in the hope that it will
//    be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
//    of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License along with
//    the jQuery formatCurrency Plugin.  If not, see <http://www.gnu.org/licenses/>.
//    wiki http://code.google.com/p/jquery-formatcurrency/wiki/Usage

(function($) {

    $.formatCurrency = {};

    $.formatCurrency.regions = [];

    // default Region is en
    $.formatCurrency.regions[‘‘] = {
        symbol: ‘‘,
        positiveFormat: ‘%s%n‘,
        negativeFormat: ‘(%s%n)‘,
        decimalSymbol: ‘.‘,
        digitGroupSymbol: ‘,‘,
        groupDigits: true
    };

    $.fn.formatCurrency = function(destination, settings) {

        if (arguments.length == 1 && typeof destination !== "string") {
            settings = destination;
            destination = false;
        }

        // initialize defaults
        var defaults = {
            name: "formatCurrency",
            colorize: false,
            region: ‘‘,
            global: true,
            roundToDecimalPlace: 2, // roundToDecimalPlace: -1; for no rounding; 0 to round to the dollar; 1 for one digit cents; 2 for two digit cents; 3 for three digit cents; ...
            eventOnDecimalsEntered: false
        };
        // initialize default region
        defaults = $.extend(defaults, $.formatCurrency.regions[‘‘]);
        // override defaults with settings passed in
        settings = $.extend(defaults, settings);

        // check for region setting
        if (settings.region.length > 0) {
            settings = $.extend(settings, getRegionOrCulture(settings.region));
        }
        settings.regex = generateRegex(settings);

        return this.each(function() {
            $this = $(this);

            // get number
            var num = ‘0‘;
            num = $this[$this.is(‘input, select, textarea‘) ? ‘val‘ : ‘html‘]();

            //identify ‘(123)‘ as a negative number
            if (num.search(‘\\(‘) >= 0) {
                num = ‘-‘ + num;
            }

            if (num === ‘‘ || (num === ‘-‘ && settings.roundToDecimalPlace === -1)) {
                return;
            }

            // if the number is valid use it, otherwise clean it
            if (isNaN(num)) {
                // clean number
                num = num.replace(settings.regex, ‘‘);

                if (num === ‘‘ || (num === ‘-‘ && settings.roundToDecimalPlace === -1)) {
                    return;
                }

                if (settings.decimalSymbol != ‘.‘) {
                    num = num.replace(settings.decimalSymbol, ‘.‘);  // reset to US decimal for arithmetic
                }
                if (isNaN(num)) {
                    num = ‘0‘;
                }
            }

            // evalutate number input
            var numParts = String(num).split(‘.‘);
            var isPositive = (num == Math.abs(num));
            var hasDecimals = (numParts.length > 1);
            var decimals = (hasDecimals ? numParts[1].toString() : ‘0‘);
            var originalDecimals = decimals;

            // format number
            num = Math.abs(numParts[0]);
            num = isNaN(num) ? 0 : num;
            if (settings.roundToDecimalPlace >= 0) {
                decimals = parseFloat(‘1.‘ + decimals); // prepend "0."; (IE does NOT round 0.50.toFixed(0) up, but (1+0.50).toFixed(0)-1
                decimals = decimals.toFixed(settings.roundToDecimalPlace); // round
                if (decimals.substring(0, 1) == ‘2‘) {
                    num = Number(num) + 1;
                }
                decimals = decimals.substring(2); // remove "0."
            }
            num = String(num);

            if (settings.groupDigits) {
                for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
                    num = num.substring(0, num.length - (4 * i + 3)) + settings.digitGroupSymbol + num.substring(num.length - (4 * i + 3));
                }
            }

            if ((hasDecimals && settings.roundToDecimalPlace == -1) || settings.roundToDecimalPlace > 0) {
                num += settings.decimalSymbol + decimals;
            }

            // format symbol/negative
            var format = isPositive ? settings.positiveFormat : settings.negativeFormat;
            var money = format.replace(/%s/g, settings.symbol);
            money = money.replace(/%n/g, num);

            // setup destination
            var $destination = $([]);
            if (!destination) {
                $destination = $this;
            } else {
                $destination = $(destination);
            }
            // set destination
            $destination[$destination.is(‘input, select, textarea‘) ? ‘val‘ : ‘html‘](money);

            if (
                hasDecimals &&
                settings.eventOnDecimalsEntered &&
                originalDecimals.length > settings.roundToDecimalPlace
            ) {
                $destination.trigger(‘decimalsEntered‘, originalDecimals);
            }

            // colorize
            if (settings.colorize) {
                $destination.css(‘color‘, isPositive ? ‘black‘ : ‘red‘);
            }
        });
    };

    // Remove all non numbers from text
    $.fn.toNumber = function(settings) {
        var defaults = $.extend({
            name: "toNumber",
            region: ‘‘,
            global: true
        }, $.formatCurrency.regions[‘‘]);

        settings = jQuery.extend(defaults, settings);
        if (settings.region.length > 0) {
            settings = $.extend(settings, getRegionOrCulture(settings.region));
        }
        settings.regex = generateRegex(settings);

        return this.each(function() {
            var method = $(this).is(‘input, select, textarea‘) ? ‘val‘ : ‘html‘;
            $(this)[method]($(this)[method]().replace(‘(‘, ‘(-‘).replace(settings.regex, ‘‘));
        });
    };

    // returns the value from the first element as a number
    $.fn.asNumber = function(settings) {
        var defaults = $.extend({
            name: "asNumber",
            region: ‘‘,
            parse: true,
            parseType: ‘Float‘,
            global: true
        }, $.formatCurrency.regions[‘‘]);
        settings = jQuery.extend(defaults, settings);
        if (settings.region.length > 0) {
            settings = $.extend(settings, getRegionOrCulture(settings.region));
        }
        settings.regex = generateRegex(settings);
        settings.parseType = validateParseType(settings.parseType);

        var method = $(this).is(‘input, select, textarea‘) ? ‘val‘ : ‘html‘;
        var num = $(this)[method]();
        num = num ? num : "";
        num = num.replace(‘(‘, ‘(-‘);
        num = num.replace(settings.regex, ‘‘);
        if (!settings.parse) {
            return num;
        }

        if (num.length == 0) {
            num = ‘0‘;
        }

        if (settings.decimalSymbol != ‘.‘) {
            num = num.replace(settings.decimalSymbol, ‘.‘);  // reset to US decimal for arthmetic
        }

        return window[‘parse‘ + settings.parseType](num);
    };

    function getRegionOrCulture(region) {
        var regionInfo = $.formatCurrency.regions[region];
        if (regionInfo) {
            return regionInfo;
        }
        else {
            if (/(\w+)-(\w+)/g.test(region)) {
                var culture = region.replace(/(\w+)-(\w+)/g, "$1");
                return $.formatCurrency.regions[culture];
            }
        }
        // fallback to extend(null) (i.e. nothing)
        return null;
    }

    function validateParseType(parseType) {
        switch (parseType.toLowerCase()) {
            case ‘int‘:
                return ‘Int‘;
            case ‘float‘:
                return ‘Float‘;
            default:
                throw ‘invalid parseType‘;
        }
    }

    function generateRegex(settings) {
        if (settings.symbol === ‘‘) {
            return new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
        }
        else {
            var symbol = settings.symbol.replace(‘$‘, ‘\\$‘).replace(‘.‘, ‘\\.‘);
            return new RegExp(symbol + "|[^\\d" + settings.decimalSymbol + "-]", "g");
        }
    }

})(jQuery);

1.引入jquery和插件(jquery省略)

<script src="jquery.formatCurrency-1.4.0.js" type="text/javascript" ></script>

2.使用插件API方法

// 如将页面所有表格的金额单元格格式化显示
$(‘.label‘).formatCurrency();

//
$(‘.ageInput‘).toNumber();
时间: 2024-08-07 18:28:13

jquery formatCurrency货币格式化处理的相关文章

javascript 货币格式化

货币格式化 example: 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> 5 </head> 6 <body> 7 Hello<br> 8 <script> 9 // format money: x,

Jquery实现日期格式化

格式一:yyyy-MM-dd HH:mm:ss Date.prototype.format = function(format) { /* * eg:format="yyyy-MM-dd hh:mm:ss"; */ var o = { "M+" : this.getMonth() + 1, // month "d+" : this.getDate(), // day "h+" : this.getHours(), // hou

[SAP ABAP开发技术总结]数据输入输出转换、小数位/单位/货币格式化

目录导航 声明:原创作品,转载时请注明文章来自SAP师太博客,并以超链接形式标明文章原始出处,否则将追究法律责任!原文出自: 15.             数据格式化.转换... 123 15.1.         数据输入输出转换... 123 15.1.1.     输出时自动转换... 123 15.1.2.     输入时自动转换... 124 15.1.3.     通过转换规则输入输出函数手动转换... 124 15.2.         数量小位数格式化... 125 15.2.

asp.net,C#中的货币格式化

asp.net直接显示Money型字段小数点后面将保留四位小数,而我们常见的格价显示一般是小数点后两位,如何实现这种效果呢,有如下几种方法: 1.直接型,通过ToString()函数直接格式话 例如把money = 12345.67 格式成 money = 12,345.67.代码如下 string _money = moeny.ToString("N"); 或者 string _moeny = money.ToString("#,###.00") 2.本地化型,通

前端js、jQuery实现日期格式化、字符串格式化

1. js仿后台的字符串的StringFormat方法 在做前端页面时候,经常会对字符串进行拼接处理,但是直接使用字符串拼接,不但影响阅读,而且影响执行效率,且jQuery有没有定义字符串的StringFormat方法,只好自己写一个. function StringFormat() { if (arguments.length == 0) return null; var str = arguments[0]; for (var i = 1; i < arguments.length; i++

vue货币格式化组件、局部过滤功能以及全局过滤功能

在页面中,例如价格数据,不管是后台传递过来的还是前台计算之后显示在页面上的,一般都只是一个数字没有格式,完整的格式应该是 要实现这个其实很简单,vue的过滤功能就很好的能解决这个问题,什么叫做过滤,就是将元数据进行相应的处理在显示出来. 首先建立一个 js 文件 currency.js const digitsRE = /(\d{3})(?=\d)/g /** * value 金额 * currency 货币符号 * decimals 保留位数 */ export function curren

JS对数字进行货币格式化并且保留两位小数点,小数用0补全

/** * 将数值四舍五入(保留2位小数)后格式化成金额形式 * * @param num 数值(Number或者String) * @return 金额格式的字符串,如'1,234,567.45' * @type String */function formatCurrency(num) { num = num.toString().replace(/\$|\,/g,''); if(isNaN(num)) num = "0"; sign = (num == (num = Math.a

格式化货币jQuery插件

很多时候我们需要去格式化货币在页面的显示效果,比如我们需要在前面加上$, ¥,或者是我们想让千分位加一个,号隔开以便于我们更好的阅读.甚至我们希望我们在输入框里也能够展示出格式化的货币,同时在输入或者删除的时候也能支持格式化. jQuery-FomratMoney,能够根据你的配置完成你想要的货币格式化.支持纯文本格式化.文本框格式化和文本框输入格式化. 下载:jQuery-FormatMoney

jquery格式化json格式日期

有时候后台传过来的json里的日期会变成/Date(1498297711000 0800)/这种类型的日期格式,前台可以通过jquery进行日期格式化: function ChangeDateFormat(cellval) { var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10)); //getMonth()从0开始算