前后端 格式化货币的方法

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();
    }
相关推荐
Penina101810 小时前
代码如何导入idea
java·intellij idea
weixin_4629019710 小时前
网页 HTML ↔ ESP32 完整通信体系详解
前端·html
禅思院10 小时前
Agent记忆管理,是一场工程上的平衡艺术
前端·架构·ai编程
.Hypocritical.11 小时前
Maven笔记——2
java·笔记·maven
crary,记忆11 小时前
React Hook 浅学 2.0 - 自定义Hook
前端·react.js·前端框架
触底反弹11 小时前
🔥 React 零基础入门(下):Props + State + useEffect 生命周期深度解析
前端·react.js·面试
咖啡星人k11 小时前
GitHub Copilot 加入 Agent 浏览器:验证 Web 应用进入编码闭环
前端·人工智能·github·copilot·前端开发·ai agent
huohuopro11 小时前
手写 Tomcat 步骤教程
java·网络
snow@li11 小时前
Java:Lombok 完整讲解
java
Shadow(⊙o⊙)11 小时前
高并发内存池:Part-1——定长内存池
java·前端·javascript