“This is the third day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”
The amount formatting presentation is a common requirement in front-end projects, and some common handling is sorted out here, such as toLocaleString(); Regular matching; Slice () loop interception, etc
Take this as an example: 12341234.246 => ¥12,341,234.25
Way 1: use the browser’s own Number. The prototype. ToLocaleString () to handle the integer part, the decimal part with Number directly. The prototype. ToFixed () round
/ * * *@params {Number} Money amount *@params {Number} Decimals preserve the number of decimal places *@params {String} Symbol prefixes symbol */
const formatMoney = (money, symbol = "", decimals = 2) = > {
if(! (money && money >0)) {
return 0.0;
}
let arr = money.toFixed(decimals).toString().split(".");
let first = parseInt(arr[0]).toLocaleString();
let result = [first, arr[1]].join(".");
return `${symbol} ${result}`;
};
formatMoney(12341234.246); / / 12341234.25
formatMoney(12341234.246."Selections".1); / / selections 12341234.2
Copy the code
Method 2: Use the regular expression to process the integer part and the decimal part. There is a “JS regular mini-book” regular expression is very good, in chapter 2.4.2 on the “thousands of digits separator notation”, introduction is very detailed, recommended to see.
\b
: Word boundary, specifically between \w and \w, and also between \w and ^, and between \w and $\B
The opposite meaning of: \b, non-word boundary(? =p)
: where p is a subpattern, that is, the position before p, or the character after the position should match P
/ * * *@params {Number} Money amount *@params {Number} Decimals preserve the number of decimal places *@params {String} Symbol prefixes symbol */
const formatMoney = (money, symbol = "", decimals = 2) = > {
let result = money
.toFixed(decimals)
.replace(/\B(? =(\d{3})+\b)/g.",")
.replace(/ ^ /.`${symbol}$`);
return result;
};
formatMoney(12341234.246."$".2); / / $12341234.25
Copy the code
Method 3: Loop a string through slice
- Substring (start, end) : contains start but does not contain end
- Substr (start, length) : contains start and is length
- Slice (start, end) : operable arrays and strings; Contains start, not end
- Splice (start, length, items) : only for arrays; Add, delete, or change
const formatMoney = (money, symbol = "", decimals = 2) = > {
let arr = money.toFixed(decimals).toString().split(".");
let num = arr[0];
let first = "";
while (num.length > 3) {
first = "," + num.slice(-3) + first;
num = num.slice(0, num.length - 3);
}
if (num) {
first = num + first;
}
return `${symbol} ${[first, arr[1]].join(".")}`;
};
formatMoney(12341234.246."$".2); / / $12341234.25
Copy the code