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

前言

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

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

思路

判断类型

后端给的接口是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}`
}
相关推荐
脑袋大大的4 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
速易达网络6 小时前
RuoYi、Vue CLI 和 uni-app 结合构建跨端全家桶方案
javascript·vue.js·低代码
耶啵奶膘6 小时前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
JoJo_Way6 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
视频砖家6 小时前
移动端Html5播放器按钮变小的问题解决方法
前端·javascript·viewport功能
GISer_Jing9 小时前
Monorepo+Pnpm+Turborepo
前端·javascript·ecmascript
天涯学馆9 小时前
前端开发也能用 WebAssembly?这些场景超实用!
前端·javascript·面试
我在北京coding10 小时前
TypeError: Cannot read properties of undefined (reading ‘queryComponents‘)
前端·javascript·vue.js
海天胜景11 小时前
vue3 获取选中的el-table行数据
javascript·vue.js·elementui