前后端 格式化货币的方法

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();
    }
相关推荐
拖孩26 分钟前
# 我又用 AI 做了个小程序:24 天,记录我这辈子认识的人
前端·后端·微信小程序
徐小夕34 分钟前
深度拆解 Design Agent:LangChain 出品,AI 设计从「好看」走向「可用」
前端·vue.js·github
JasonChen@66638 分钟前
2.Tomcat 安装部署与一键自动化脚本实战
java·tomcat
1-1=01 小时前
Vue 表单数据和过滤器
前端·javascript·vue.js
SimonKing1 小时前
零 OCR 依赖!Firecrawl 这个 Rust 库把 Word / PPT / Excel 全变成 Markdown
java·后端·程序员
Rain的Java大神之路1 小时前
别被 ChatGPT 的打字机效果骗了:一字一字蹦,才是 LLM 自回归的命门(附大厂 Java 流式落地)
java·后端·面试
oil欧哟1 小时前
Oil UI 的设计思路与日常使用方式:让 AI 摆脱默认模板并保持多页面风格统一
前端
渣渣盟2 小时前
狂命爆肝99天,共52K字的JAVA学习笔记奉上,JAVA从入门到精通一文搞定,一文在手JAVA无忧
java·笔记·学习
恋猫de小郭2 小时前
Jetpack Compose 1.13 发布,憋了这么久终有交代了
android·前端·flutter
头发还在的女程序员2 小时前
智慧物业源码解析:房屋档案与业主变更怎样保持历史业务连续
前端·javascript·vue.js·物业管理·小区物业·智慧物业