前端实现千位分隔符并保留指定小数位

前言

最近写需求遇到了一个金额的显示需求,要求使用千位分隔符并保留两位小数。贴下千位分隔符的介绍

这个需求并不是太难,下面写下我的思路。

思路

判断类型

后端给的接口是number类型的数据,为了更好处理数据,首先进行类型转型,将number类型转换为string类型的数据

js 复制代码
const prcoessedBalance = String(balance)

分割

由于要保留两位小数,需要将金额分割为整数部分和小数部分

js 复制代码
const [integerPart, decimalPart = ''] = prcoessedBalance.split('.')

这里有个需要注意的地方,对于 123 这种没有小数位的数据,使用解构赋值得到的小数位变量是 undefined,默认值就会起作用,便于后续处理。

这里的默认值只有严格等于 undefined 才会起作用,null 是不会起作用的

es6标准入门-变量的解构赋值

小数位

上面我们已经做了小数的获取,现在来处理小数位,我的需求是没有0补上两个0,有一个小数位就补上一个0,两个小数位不做任何处理,超过两位直接截取前两位。

js 复制代码
const processedDecimalPart = decimalPart.slice(0, 2).padEnd(2, '0')

这里用到了一个叫 padEnd 的 方法,其作用是用来从字符串末尾填充指定字符串,如果需要会重复填充,直到达到给定的长度。

MDN-padEnd

添加千位分隔符

这里我的思路是从前往后遍历,处理字符是从后面往前获取。因为不考虑用数组,也不考虑用 reverse 等方法,所以拼接字符串时需要把当前处理的内容拼在最前面。这里有个边界case,当处理到第一个字符串的时候,不能添加千位分隔符,比如对于 123456 这个数字,我们要的结果是 123,456 而不是 ,123,456

js 复制代码
let prcoessedIntegerPart = ''
let count = 0
const length = integerPart.length

for(let index = 0; index < length; index++) {
    const currentStr = integerPart.charAt(length - 1- index)
    if(count === 2 && index !== length - 1) {
       prcoessedIntegerPart = `,${currentStr}${prcoessedIntegerPart}`
       count = 0
    } else {
       prcoessedIntegerPart = `${currentStr}${prcoessedIntegerPart}`
       count += 1
    }
}

组合

最后拼接一下整数部分和小数部分就大功告成了。

测试

源码

js 复制代码
function formatBalance(balance: number) {
    const prcoessedBalance = String(balance)
    const [integerPart, decimalPart = ''] = prcoessedBalance.split('.')
    
    const processedDecimalPart = decimalPart.slice(0, 2).padEnd(2, '0')
  
    let prcoessedIntegerPart = ''
    let count = 0
    const length = integerPart.length
    
    for(let index = 0; index < length; index++) {
       const currentStr = integerPart.charAt(length - 1- index)
       if(count === 2 && index !== length - 1) {
          prcoessedIntegerPart = `,${currentStr}${prcoessedIntegerPart}`
          count = 0
       } else {
          prcoessedIntegerPart = `${currentStr}${prcoessedIntegerPart}`
          count += 1
       }
    }
    
    return `${prcoessedIntegerPart}.${processedDecimalPart}`
}
相关推荐
Kakarotto1 小时前
Canvas 直线点击事件处理优化
javascript·vue.js·canvas
进击的尘埃1 小时前
Playwright Component Testing 拆到底:组件怎么挂上去的,快照怎么在 CI 里不翻车
javascript
左夕1 小时前
最基础的类型检测工具——typeof, instanceof
前端·javascript
yuki_uix1 小时前
递归:别再"展开脑补"了,学会"信任"才是关键
前端·javascript
用户5757303346244 小时前
🐱 从“猫厂”倒闭到“鸭子”横行:一篇让你笑出腹肌的 JS 面向对象指南
javascript
码路飞4 小时前
GPT-5.4 Computer Use 实战:3 步让 AI 操控浏览器帮你干活 🖥️
java·javascript
进击的尘埃4 小时前
Service Worker 离线缓存这事,没你想的那么简单
javascript
进击的尘埃5 小时前
HTTP/3 的多路复用和 QUIC 到底能让页面快多少?聊聊连接迁移和 0-RTT
javascript
Maxkim6 小时前
前端工程化落地指南:pnpm workspace + Monorepo 核心用法与实践
前端·javascript·架构
小兵张健18 小时前
开源 playwright-pool 会话池来了
前端·javascript·github