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

前言

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

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

思路

判断类型

后端给的接口是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}`
}
相关推荐
diygwcom几秒前
electron-updater实现electron全量版本更新
前端·javascript·electron
volodyan3 分钟前
electron react离线使用monaco-editor
javascript·react.js·electron
^^为欢几何^^12 分钟前
lodash中_.difference如何过滤数组
javascript·数据结构·算法
Hello-Mr.Wang17 分钟前
vue3中开发引导页的方法
开发语言·前端·javascript
程序员凡尘44 分钟前
完美解决 Array 方法 (map/filter/reduce) 不按预期工作 的正确解决方法,亲测有效!!!
前端·javascript·vue.js
北岛寒沫5 小时前
JavaScript(JS)学习笔记 1(简单介绍 注释和输入输出语句 变量 数据类型 运算符 流程控制 数组)
javascript·笔记·学习
everyStudy5 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript
无心使然云中漫步6 小时前
GIS OGC之WMTS地图服务,通过Capabilities XML描述文档,获取matrixIds,origin,计算resolutions
前端·javascript
Bug缔造者7 小时前
Element-ui el-table 全局表格排序
前端·javascript·vue.js
xnian_7 小时前
解决ruoyi-vue-pro-master框架引入报错,启动报错问题
前端·javascript·vue.js