昨天看到大欢写了一个js工具函数---价格格式化。就是解决后台返回的产品价格数字格式各异,而前端需要展示出带逗号分离的格式数据(比如:10000000.99转化成10,000,000.99),这样用户看的时候就方便一些。
对于准备看看js的人来说,他写的东西我现在也只能看出个大概意思,但是还是不能完全看懂的,所以就决定自己写一个渣渣代码试试,就当记录一下么。
function formatPrice(box){
if(!box)
return 0
if(typeof box !== 'string'){
box = String(box);
}
var patten =/[1-9]([0-9]){3,}/g; //写了一个正则,能匹配出大于1000的数字的整数部分,刚好这部分也是需要处理的部分。
var a = box.match(patten);//获取数组
for (let index = 0; index < a.length; index++) {
box = box.replace(a[index], (a[index] * 1).toLocaleString());
}
return box;
}
主要代码就是这点。正则也不咋会写,反正整体都是瞎jb写着玩玩而已。
input | output |
---|---|
formatPrice(100000.9) |
100,000.9 |
formatPrice('100000.9') |
100,000.9 |
formatPrice('100000.9元') |
100,000.9元 |
formatPrice('原价100000.9元') |
原价100,000.9元 |
formatPrice('') |
0 |
formatPrice() |
0 |
formatPrice('原价100000.9元 优惠9999元 现价90001.9元') |
原价100,000.9元 优惠9,999元 现价90,001.9元 |
大概就是这些了,当然只是为了记录一下自己写js玩玩而已。不做参考。
最后附上大佬写的代码
function formatPrice (price) {
if (!price) {
return 0
}
if (/,/.test(price)) {
return price
}
price = String(price)
const intPrice = price.match(/\d+/)[0]
const HOLDER = 'HOLDER'
const holder = price.replace(intPrice, HOLDER)
const intPriceArr = intPrice.split('').reverse()
let res = ''
intPriceArr.forEach((item, index) => {
if (index % 3 === 0 && index) {
res = item + ',' + res
} else {
res = item + res
}
})
return holder.replace(HOLDER, res)
}
function formatPrice (value) {
if (!value) {
return 0
}
if (/,/.test(value)) {
return value
}
value = String(value)
const reg = /\d+\.?\d*/
const HOLDER = 'HOLDER'
const price = value.match(reg)[0]
const holder = value.replace(price, HOLDER)
value = holder.replace(HOLDER, Number(price).toLocaleString())
return value
}
网友评论