Two Simple Realization Methods of JavaScript Numerical Thousand Position Formatting
- 2021-07-06 10:13:14
- OfStack
When formatting numerical values, a common problem is formatting according to thousandths. There are many solutions to this problem on the Internet, and Array. prototype. reduce methods can also be used to realize thousandth formatting.
function formatNumber(num) {
if (isNaN(num)) {
throw new TypeError("num is not a number");
}
var groups = (/([\-\+]?)(\d*)(\.\d+)?/g).exec("" + num),
mask = groups[1], // Signed bit
integers = (groups[2] || "").split(""), // Integer part
decimal = groups[3] || "", // Fractional part
remain = integers.length % 3;
var temp = integers.reduce(function(previousValue, currentValue, index) {
if (index + 1 === remain || (index + 1 - remain) % 3 === 0) {
return previousValue + currentValue + ",";
} else {
return previousValue + currentValue;
}
}, "").replace(/\,$/g, "");
return mask + temp + decimal;
}
The reduce method of Array is not supported below IE9, however, we can implement an reduce method based on ECMAScript 3.
In JavaScript, the matching mode parameter of replace method of string can also be a regular expression besides string. The following is the specific code for realizing thousandth formatting by String. prototype. replace method:
function formatNumber(num) {
if (isNaN(num)) {
throw new TypeError("num is not a number");
}
return ("" + num).replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, "$1,");
}
(\ d {1, 3}) is a capture packet that can be backreferenced with $1,? = (\ d {3}) + (? : $\.) is a forward assertion that matches 1 to 3 digits must be followed by 3 digits, but not the last 3 digits or 3 digits and decimal points.