vue3
html
// 方法:格式化货币
const formatCurrency = (value) => {
if (value === null || value === undefined || value === '') {
return '¥0'
}
let strValue = String(value).replace(/[,\s]/g, '')
const isNegative = strValue.startsWith('-')
if (isNegative) {
strValue = strValue.substring(1)
}
let [integerPart, decimalPart = ''] = strValue.split('.')
// 添加千位分隔符
integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
// 移除小数部分末尾的0
if (decimalPart) {
decimalPart = decimalPart.replace(/0+$/, '')
}
let result = integerPart
if (decimalPart) {
result += '.' + decimalPart
}
return (isNegative ? '-¥' : '¥') + result
}
使用
html
<el-table-column label="本月收支" prop="sqmPerPackage" width="220">
<template #default="{ row }">
<div>
<span style="color: green">{{`收入:`+ formatCurrency(row.thisMonthIncome) }}</span>
</div>
<div>
<span style="color: red">{{`支出:`+ formatCurrency(row.thisMonthExpense) }}</span>
</div>
</template>
</el-table-column>
java
java
private String formatCurrency(BigDecimal amount) {
return (amount.compareTo(BigDecimal.ZERO) >= 0 ? "" : "-") + "¥" + amount.abs().setScale(2, RoundingMode.HALF_UP).toPlainString();
}