Files
income_payments_client/src/utils/formatMoney.js
T

68 lines
1.5 KiB
JavaScript

export function formatMoney(money) {
if(money === 0) return '0.00'
if(money === '') return ''
var num = (money || 0).toString(),
re = /\d{3}$/,
result = ''
var point = ''
// 存在小数点 分开整数和小数点
if (num.indexOf('.') !== -1) {
point = num.substring(num.indexOf('.'))
num = parseInt(num)
}else {
// point = '.00'
}
// 循环添加逗号
while (re.test(num)) {
result = RegExp.lastMatch + result
if (num !== RegExp.lastMatch) {
result = ',' + result
num = RegExp.leftContext
} else {
num = ''
break
}
}
if (num) {
result = num + result
}
// 去掉负数符号后面的逗号
function _(result) {
return result.replace('-,', '-')
}
// 如果第一位是逗号 去掉逗号
function __(result) {
if (result[0] === ',') {
result = result.substring(1)
}
return result
}
// 第一位是 小数点开头的 前面加上 0
function ___(result) {
if (result[0] === '.') {
result = '0' + result
}
return result
}
return ___(__(_(result) + point))
}
/* 将数字 转换成 3个数字一组,并且中间用,分隔得方式 */
export function handleCostNumber(value) {
if(!value){
return 0.00
}
//toFixed()方法可以把Number四舍五入为指定位数的数字
let str=parseFloat(value).toFixed(2)
//"?="表示查询的要满足的条件,
return str&&str.toString().replace(/(\d)(?=(\d{3})+\.)/g,function ($0,$1) {
return $1+','
})
}