JS计算对象数组中某个指定字段的总计金额,并使用千位分隔符展示

需求1 - 计算合计

计算对象数组 arr 中 amount 字段的合计值

const arr = [
	{
    
     id: 1, name: '泡泡哥', amount: 999.9},
	{
    
     id: 2, name: '胡老板', amount: 1024 },
    {
    
     id: 3, name: '渣渣彬', amount: 223.21 },
    {
    
     id: 4, name: 'FW老羊', amount: 1.1 },
]

实现方法

**
 * 计算给定字段的总计
 * @param {
    
    Array} array 对象数组数据
 * @param {
    
    String} computedField  需要进行合计的字段名
 * @return {
    
    Number} 合计后的结果
 */
function totalSum(array, computedField) {
    
    
    if (!array || array.length === 0) {
    
    
        return 0
    } else {
    
    
        return array.reduce((value, item) => value + +item[computedField], 0)
    }
}
// 使用方法
const total = totalSum(arr, 'amount')
console.log(total)  //=> 2248.21

需求2 - 金额千位分隔符展示

将需求1中得到的合计金额 2248.21 使用千位分隔符的形式展示,并保留两位小数

// 期望结果 
2,248.21

实现方法

/**
 * 将金额的整数部分逢三一断(千分位分隔符), 并保留两位小数
 * @param {String}  amount 要格式化的金额
 */
function amountFormat(amount) {
    
    
	if (!amount || isNaN(amount)) return '0.00'
	return (+amount).toFixed(2).replace(/^-?\d+/g, item => item.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
 }
// 使用
console.log(amountFormat(2248.21))    //=> 2,248.21
console.log(amountFormat(2248.1))     //=> 2,248.10
console.log(amountFormat(123))        //=> 123.00
console.log(amountFormat(123.1))      //=> 123.10
console.log(amountFormat(99999999))   //=> 99,999,999.00
console.log(amountFormat(0))          //=> 0.00
console.log(amountFormat('0.1'))      //=> 0.10
console.log(amountFormat('4553.12'))  //=> 4,553.12
console.log(amountFormat('ppg'))      //=> 0.00

猜你喜欢

转载自blog.csdn.net/weixin_43417844/article/details/129946119
今日推荐