前后端 格式化货币的方法

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();
    }
相关推荐
一点一木3 小时前
深度体验TRAE SOLO移动端7天:作为独立开发者,我把工作流揣进了兜里
前端·人工智能·trae
天外飞雨道沧桑4 小时前
TypeScript 中 omit 和 record 用法
前端·javascript·typescript
Lee川4 小时前
mini-cursor 揭秘:从 Tool 定义到 Agent 循环的完整实现
前端·人工智能·后端
一直不明飞行5 小时前
Java的equals(),hashCode()应该在什么时候重写
java·开发语言·jvm
REDcker5 小时前
有限状态机与状态模式详解 FSM建模Java状态模式与C++表驱动模板实践
java·c++·状态模式
canonical_entropy5 小时前
从 Spec-Driven Development 到 Attractor-Guided Engineering
前端·aigc·ai编程
研☆香5 小时前
聊聊前端页面的三种长度单位
前端
你的保护色5 小时前
【无标题】
java·服务器·网络
给钱,谢谢!5 小时前
React + PixiJS 实现果园成长页:从状态机到浇水动画
前端·react.js·前端框架
basketball6165 小时前
C++ 构造函数完全指南:从入门到进阶
java·开发语言·c++