博 之 文

以 拼 搏 设 计 梦 想 , 以 恒 心 编 程 明 天
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Js格式化数字保留两位小数

Posted on 2013-01-23 14:21  IsNull_Soft  阅读(296)  评论(0)    收藏  举报
        //格式化数字保留两位小数
        function formatCurrency(num) {
            if (!num) return "0.00";
            num = num.toString().replace(/\$|\,/g, '');
            if (isNaN(num))
                num = "0.00";
            sign = (num == (num = Math.abs(num)));
            num = Math.floor(num * 100 + 0.50000000001);
            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);
        }