让前端飞

数字格式化

2018-11-16  本文已影响0人  Adoins

数字转换为千分符格式的函数如下,currency是在数字前加的符号,可为¥、$等,比如moneyFormat('1850000000', '¥'),输出为¥185,000.00

function moneyFormat(value, currency, decimals) {
    if(!value || value == ''){
        return '--';
    }
    var digitsRE = /(\d{3})(?=\d)/g;
    value = parseFloat(value);
   if (!isFinite(value) || (!value && value !== 0)) return '';
    currency = currency != null ? currency : '';
    decimals = decimals != null ? decimals : 2;
    var stringified = Math.abs(value).toFixed(decimals);
    var _int = decimals ? stringified.slice(0, -1 - decimals) :stringified;
    var i = _int.length % 3;
    var head = i > 0 ?(_int.slice(0, i) + (_int.length > 3 ? ',' : '')) :'';
    var _float = decimals ?stringified.slice(-1 - decimals) :'';
    var sign = value < 0 ? '-' : '';
    return sign + currency + head + _int.slice(i).replace(digitsRE, '$1,') + _float;
}

需要注意的是有可能数字过长导致parsefloat直接转换输出科学计数法的数字,因此作如下处理

function convertNum(amount) {
    // 判断是否科学计数法,是则进行转换
    var strAmount = new String(amount)
    if((strAmount.indexOf('E') != -1) || (strAmount.indexOf('e') != -1)) {
        return new Number(amount).toLocaleString();
    } else{
        return amount;
    }
}

最终完整代码为

function moneyFormat(value, currency, decimals) {
    if(!value || value == ''){
        return '--';
    }
    var digitsRE = /(\d{3})(?=\d)/g;
    value = parseFloat(value);
    // 有可能出现1.546714415467144e+87这种科学计数法的格式,因此做转换
    value = convertNum(value);
    if(typeof value === 'string'){
        return value;
    }
   if (!isFinite(value) || (!value && value !== 0)) return '';
    currency = currency != null ? currency : '';
    decimals = decimals != null ? decimals : 2;
    var stringified = Math.abs(value).toFixed(decimals);
    var _int = decimals ? stringified.slice(0, -1 - decimals) :stringified;
    var i = _int.length % 3;
    var head = i > 0 ?(_int.slice(0, i) + (_int.length > 3 ? ',' : '')) :'';
    var _float = decimals ?stringified.slice(-1 - decimals) :'';
    var sign = value < 0 ? '-' : '';
    return sign + currency + head + _int.slice(i).replace(digitsRE, '$1,') + _float;
}
function convertNum(amount) {
    // 判断是否科学计数法,是则进行转换
    var strAmount = new String(amount)
    if((strAmount.indexOf('E') != -1) || (strAmount.indexOf('e') != -1)) {
        return new Number(amount).toLocaleString();
    } else{
        return amount;
    }
}

js转换数字为科学计数法的规则参考链接 https://blog.csdn.net/jingwang2016/article/details/53506023

上一篇 下一篇

猜你喜欢

热点阅读