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

前言

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

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

思路

判断类型

后端给的接口是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}`
}
相关推荐
bnnnnnnnn1 分钟前
做了个 Vue3 上传大文件的项目,顺手搞懂了 OSS、Pinia 和断点续传
前端·javascript·vite
独立开阀者_FwtCoder2 分钟前
Cursor MCP推荐
前端·javascript·人工智能
MrsBaek14 分钟前
前端笔记-JavaScript部分(中)
前端·javascript·笔记
拖孩29 分钟前
【Nova UI】九、打造组件库第一个组件-图标组件(中):属性、功能与样式的完美融合
前端·javascript·vue.js
骑自行车的码农32 分钟前
JavaScript柯里化的实现
javascript
风兮w40 分钟前
插件架构实践
前端·javascript·架构
天天扭码1 小时前
一分钟解决 | 高频面试算法题——最长连续序列(哈希表)
前端·javascript·算法
WEI_Gaot1 小时前
3 使用工厂模式 和 构造函数 优化创建对象
前端·javascript
1024小神1 小时前
我使用github api同步文件到仓库后,立即触发工作流,这个时候工作流执行actions/checkout@v4,此时工作流中拿到的代码是最新的吗
前端·javascript
kovli2 小时前
红宝书第十二讲:详解JavaScript中的工厂模式与原型模式等各种设计模式
前端·javascript