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

前言

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

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

思路

判断类型

后端给的接口是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}`
}
相关推荐
小二·17 小时前
Vue 3 组件通信全方案详解:Props/Emit、provide/inject、事件总线替代与组合式函数封装
前端·javascript·vue.js
DevUI团队18 小时前
🔥Angular高效开发秘籍:掌握这些新特性,项目交付速度翻倍
前端·typescript·angular.js
Moment18 小时前
如何在前端编辑器中实现像 Ctrl + Z 一样的撤销和重做
前端·javascript·面试
小猪猪屁19 小时前
权限封装不是写个指令那么简单:一次真实项目的反思
前端·javascript·vue.js
我的写法有点潮19 小时前
如何取消Vue Watch监听
前端·javascript·vue.js
xkxnq19 小时前
第一阶段:Vue 基础入门(第 6 天)
前端·javascript·vue.js
神仙刘19 小时前
解决Vue router history 静态资源访问404,请求链接被加上了path的前一部分
前端·javascript·vue.js
C_心欲无痕19 小时前
react - useDeferredValue自动延迟更新
javascript·react.js·ecmascript
EndingCoder19 小时前
TypeScript 的基本类型:数字、字符串和布尔
linux·ubuntu·typescript
G_GreenHand20 小时前
vue自定义日历
前端·javascript·vue.js