在util.ts文件下添加通用函数
// 添加千位符 (,)
const thousandsFormat = (num: any) => {
const reg = /\d{1,3}(?=(\d{3})+$)/g;
return `${num}`.replace(reg, '$&,');
};
//传入数字 这里的flag是指有小数点时要不要自动填充为2位小数
export const n_toThousands = (num: any,flag?:any) => {
if (typeof num === 'string') {
num = Number(num);
}
return toThousands(num,flag);
};
//将传入的数字拼凑成千位符,保留小数点
export const toThousands = (num: any,flag?:any) => {
if (typeof num === 'string') {
return num.replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
}
let c = '';
if (num.toString().indexOf('.') !== -1) {
const arr = num.toString().split('.');
const point = flag && arr[1].length < 2 ? `${arr[1]}0` : arr[1]
c = thousandsFormat(arr[0]) + '.' + point
} else {
c = thousandsFormat(num);
}
return c;
};
//去除千位符
export const removeThousandSeparator = (str:string) => {
if(!str) return ''
return str.toString().replace(/,/g, '');
}
在需要运用的页面引用
import { n_toThousands ,removeThousandSeparator} from ‘@/utils/util’;
//转换成千位符
let str = '48536842.18'
str = n_toThousands(str,true)
// console.log(str) ------> 48,536,842.18
//去除千位符
let str = '48,536,842.18'
str = Number(removeThousandSeparator(str))
// console.log(str) ------> 48536842.18
另一种转千位符的方式
function toThousands(str: any) {
let minusFlag = false;
str = str.toString();
if (str.includes("-")) {
minusFlag = true;
let splitData = str.split("-");
str = splitData[1];
}
var newStr = "";
var count = 0;
if (str.indexOf(".") == -1) {
for (let i = str.length - 1; i >= 0; i--) {
if (count % 3 == 0 && count != 0) {
newStr = str.charAt(i) + "," + newStr;
} else {
newStr = str.charAt(i) + newStr;
}
count++;
}
if (minusFlag) {
return (str = `-${newStr}`);
}
return (str = newStr);
} else {
for (let i = str.indexOf(".") - 1; i >= 0; i--) {
if (count % 3 == 0 && count != 0) {
newStr = str.charAt(i) + "," + newStr; //碰到3的倍数则加上“,”号
} else {
newStr = str.charAt(i) + newStr; //逐个字符相接起来
}
count++;
}
let point = str.split(".")[1];
str = newStr + "." + point;
if (minusFlag) {
return `-${str}`;
}
return str;
}
}