数字千分位格式化

题目如下

  • 数字千分位格式化,输出字符串
  • 如输入数字12050100,输出字符串 12,050,100
  • 注意:逆序判断

思路如下

  • 转换为数组,reverse,每3位拆分
  • 使用正则表达式
  • 使用字符拆分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* @description 千分位格式化
* @author sola-grj
*/

/**
* 千分位格式化(使用数组)
* @param n number
*/
export function format1(n: number): string {
n = Math.floor(n) // 只考虑整数

const s = n.toString()
const arr = s.split('').reverse()
return arr.reduce((prev, val, index) => {
if (index % 3 === 0) {
if (prev) {
return val + ',' + prev
} else {
return val
}
} else {
return val + prev
}
}, '')
}

/**
* 数字千分位格式化(字符串分析)
* @param n number
*/
export function format2(n: number): string {
n = Math.floor(n) // 只考虑整数

let res = ''
const s = n.toString()
const length = s.length

for (let i = length - 1; i >= 0; i--) {
const j = length - i
if (j % 3 === 0) {
if (i === 0) {
res = s[i] + res
} else {
res = ',' + s[i] + res
}
} else {
res = s[i] + res
}
}

return res
}

// // 功能测试
// const n = 10201004050
// console.info('format1', format1(n))
// console.info('format2', format2(n))

单元测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @description 数字千分位格式化
* @author sola-grj
*/

import { format1, format2 } from './thousands-format'

describe('数组千分位格式化', () => {
it('正常', () => {
const n = 10201004050
const res = format2(n)
expect(res).toBe('10,201,004,050')
})
it('小于 1000', () => {
expect(format2(0)).toBe('0')
expect(format2(10)).toBe('10')
})
})