-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththousandify.js
More file actions
50 lines (47 loc) · 1.6 KB
/
thousandify.js
File metadata and controls
50 lines (47 loc) · 1.6 KB
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
let charsetRegExp = /^[\d.]+$/ // 校验是否为数字
let defaultOption = {
thousandSeparator: ',', // 千分位分隔符
decimalSeparator: '.', // 小数分隔符
decimalDigits: false // 小数位数, false表示不特殊处理
}
function isNumber(target) {
return Object.prototype.toString.call(target) === '[object Number]'
}
function thousandify(amount, option) {
let parsedAmount = amount + '' // 数字转字符串
if (!charsetRegExp.test(parsedAmount)) {
return amount
}
let { decimalSeparator, thousandSeparator, decimalDigits } = {
...defaultOption,
...option
}
// 将小数部分与整数部分分隔开
let amountParts = parsedAmount.split(decimalSeparator)
// 整数部分,从末尾开始每三位数前面插入千分位
let intPartStr = amountParts[0].replace(
/(?!^)(?=(\d{3})+$)/g,
thousandSeparator
)
// 小数部分
let decimalStr = amountParts[1] || ''
// 截取小数位数,不处理精度,仅截取
if (isNumber(decimalDigits)) {
decimalStr = decimalStr.substring(0, decimalDigits)
}
return decimalStr
? [intPartStr, decimalStr].join(decimalSeparator)
: intPartStr
}
// 正则太复杂?用循环实现
function fn(s) {
let res = '',
len = s.length
for (let i = len - 1; i >= 0; i--) {
const sep = (len - i - 1) % 3 ? '' : ','
res = s[i] + sep + res
}
return res.slice(0, -1)
}
console.log(fn('1235182918'))
console.log(thousandify(182918.928, { decimalDigits: 2 }))