学无先后,达者为师

网站首页 前端文档 正文

JS转换数字为逗号分隔并保留两位小数

作者:ZionHH 更新时间: 2022-05-12 前端文档

JS正则转换数字为逗号分隔的金额

demo

// 格式化金额
function formatMoney(n) {
	const regex = /\d{1,3}(?=(\d{3})+(\.|$))/g // 替换规则
	n = String(Math.round(n * Math.pow(10, 2))) // 乘100 四舍五入
	let integer = n.substr(0, n.length - 2).replace(regex, '$&,') // 最后两位前的为整数
	let decimal = n.substr(n.length - 2) // 最后两位为小数
	const result = `${integer || 0}.${decimal}`
	return result
}
// 还原金额
function restoreMoney(s) {
	const regex = /[^\d\.-]/g
	const result = Number(String(s).replace(regex, ''))
	return result
}

原文链接:https://blog.csdn.net/z291493823/article/details/121702399

栏目分类
最近更新