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
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值