JavaScript 金额、数字、千分位、千分位、保留几位小数、舍入舍去、支持负数

 

JavaScript 金额、数字 千分位格式化、保留指定位数小数、支持四舍五入、进一法、去尾法

字段说明:

  number:需要处理的数字;

  decimals:保留几位小数,默认两位,可不传;

  dec_point:小数点符号,默认为‘.’,可不传;

  thousands_sep:千分位符号,默认为‘,’,可不传;

  round_tag:舎入方式,默认为四舍五入('round'),可不传; 向上取值('ceil');向下取值('floor');

 

function decimal_format(number, decimals, dec_point, thousands_sep,round_tag) {
  
    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
	decimals = decimals || 2; //默认保留2位
	dec_point = dec_point || "."; //默认是'.';
	thousands_sep = thousands_sep || ","; //默认是',';
    round_tag = round_tag || "round"; //默认是四舍五入
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
 
            var k = Math.pow(10, prec);
            console.log();
 
            return '' + parseFloat(Math[round_tag](parseFloat((n * k).toFixed(prec*2))).toFixed(prec*2)) / k;
        };
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    var re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2");
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

  执行效果:

console.log(decimal_format(43868.6380))//"43,868.64"
console.log(decimal_format(43868.6380,3))//"43,868.638"
console.log(decimal_format(43868.6380,4,'。')) //"43,868。6380"
console.log(decimal_format(43868.6380,2,".","/"))//"43/868.64"
console.log(decimal_format(-43868.6380))//"-43,868.64"
console.log(decimal_format(43868.6380, 2, ".", ",", "floor")) //"43,868.63"

  

 

posted @ 2018-12-12 14:36  CansonHai  阅读(889)  评论(0编辑  收藏  举报