前后端 格式化货币的方法

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();
    }
相关推荐
曹牧22 分钟前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
passerby606126 分钟前
完成前端时间处理的另一块版图
前端·github·web components
掘了34 分钟前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅37 分钟前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅1 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
爬山算法1 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
kfyty7251 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎1 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄1 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea
崔庆才丨静觅1 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端