前后端 格式化货币的方法

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 小时前
井字棋AI机器人实现详解 - Minimax算法实战-鸿蒙PC Electron框架完成
前端·人工智能·算法·华为·electron·鸿蒙
xieliyu.5 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
明夜之约5 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee5 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Jinkxs5 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
辣机小司5 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录
ZC跨境爬虫6 小时前
跟着 MDN 学JavaScript day_7:数学运算与逻辑判断实战测试
开发语言·前端·javascript·学习·ecmascript
fangdengfu1236 小时前
ES分析系统各个服务日志占用量
java·前端·elasticsearch
云烟成雨TD7 小时前
Spring AI 1.x 系列【51】可观测性技术选型
java·人工智能·spring
星越华夏7 小时前
ESP32-CAM图像传输项目说明文档
java·后端·struts·esp32