Open nmsn opened 1 year ago
new Intl.NumberFormat().format(111111111.111)
// '111,111,111.111'
const number = 123456.789;
number.toLocaleString(); // '123,456.789'
function thousandsSeparator(n: number): string {
const strSplit = n.toString().split(".");
const integer = strSplit[0].split("");
integer.reverse();
const decimal = strSplit[1];
const newInteger = [];
for (let i = 0; i < integer.length; i++) {
if (i % 3 === 0 && i !== 0) {
newInteger.push(",");
}
newInteger.push(integer[i]);
}
newInteger.reverse();
let s = newInteger.join("");
if (decimal) {
s += `.${decimal}`;
}
return s;
}
function thousandsSeparator2(n: number): string {
const strSplit = n.toString().split(".");
const integer = strSplit[0];
const decimal = strSplit[1] || "";
return integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + decimal;
}
如题,实现多种方式