fix(util): 精度问题处理

This commit is contained in:
yeweikangxx123 2025-07-23 23:43:06 +08:00
parent 02cb22a1b9
commit 91cc8feefa
1 changed files with 30 additions and 3 deletions

View File

@ -81,10 +81,37 @@ function formatSeconds(second_time) {
function formatCurrency(value) {
// 处理空值或无效值
if (!value) {
return '0.00'
}
if (value === null || value === undefined || value === '') {
return value
}
// 转换为数字类型
const numValue = typeof value === 'string' ? parseFloat(value) : value
// 验证是否为有效数字
if (isNaN(numValue)) {
return value
}
// 截断到两位小数(不四舍五入)
const truncated = Math.floor(numValue * 100) / 100
// 添加千分位分隔符的函数
function addThousandSeparator(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 判断是否有小数部分
if (truncated % 1 === 0) {
// 整数,不显示小数位,但添加千分位分隔符
return addThousandSeparator(numValue)
} else {
// 有小数,保留两位,并为整数部分添加千分位分隔符
const fixedValue = numValue.toFixed(2)
const parts = fixedValue.split('.')
parts[0] = addThousandSeparator(parts[0])
return parts.join('.')
}
}
export { formatCurrency, formatMsToDate, formatSeconds, isEmpty }