jQuery js 格式化数字

写程序与的时候,有些地方需要js或者jQuery取值,然后将50000000.00格式化成50,000,000.00这种形式;

首先创建formatCurrency.js,代码如下:

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    var cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
            num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + num + '.' + cents);
}

在使用的jsp中引入上面的formatCurrency.js后,进行取值显示,如下:

$('#showInput').val(formatCurrency(500000000.00));

在将数值存入到数据库之前,要将50,000,000.00再格式化回50000000.00,再进行持久化,代码如下:

var lastNum = parseFloat(500,000,000.00.replace(/,/g,""));

 

posted @ 2015-09-29 13:22  泶雪乖女  阅读(1682)  评论(0编辑  收藏  举报