实现小数的千位符:
<!DOCTYPE html>
<html lang="“cn”">
<head>
<meta charset="“utf-8”" />
<title>title</title>
<style></style>
<script>
function thousandBitSeparator(num) {
return (
num &&
(num.toString().indexOf(".") != -1
? num.toString().replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
return $1 + ",";
})
: num.toString().replace(/(\d)(?=(\d{3}))/g, function ($0, $1) {
return $1 + ",";
}))
);
}
const formatNumber = (num, n = 2) => {
try {
if (typeof num !== "number" && !num) return "-";
num = (typeof num === "number" ? num : +num).toFixed(
Math.max(0, ~~n)
);
const nums = `${num}`.split(".");
if (nums[1]) {
const left = nums[0].replace(/\d(?=(\d{3})+$)/g, "$&,");
const right = nums[1].replace(/(?<=^(\d{3})+)\d/g, ",$&");
return `${left}.${right}`;
} else {
return num.replace(/\d(?=(\d{3})+$)/g, "$&,");
}
} catch {
return "-";
}
};
const a = formatNumber(1234567890.123456789123, 12);
console.log(a);
console.log(typeof a);
</script>
</head>
<body>
2222222
</body>
</html>