This is the 4th day of my participation in the August More Text Challenge
No decimal
This kind of situation is relatively simple, let’s go to determine whether the length is 3, if we can return directly to 3 digital string, if not for three and we began to the remainder of an array, if we can be divided exactly by 3 said then we need to consider beyond the part of the separated only need three three parts again with all good; If our current array is not divisible by 3, we strip out the remainder and divide it into three equal parts with commas.
Note the use of regular forms, where we use regular expressions to cut strings into arrays and use joins to convert them into formatted strings.
Code implementation:
// When there are no decimals
function ToLocalNum(num) {
let str = num.toString();
let len = str.length;
if (len === 3) {
return str
} else {
let yushu = len % 3
if (yushu == 0) {
return str.match(/\d{3}/g).join(', ')}else {
return str.slice(0, yushu) + ', ' + str.slice(yushu, len).match(/\d{3}/g).join(', ')}}}console.log(ToLocalNum(12312345678))
Copy the code
Containing the decimal
We don’t need to do much with decimals, we just need to find the corresponding part of decimals, and we can concatenate it with what we did before and we can do what we want.
The code is as follows:
let format = num= > {
let str = num.toString();
let len = str.length;
// The decimal point
let floatstr = ' '
// Check if it is an integer
let tartgetArr = ' '
let donum = num.indexOf('. ');
if(donum ! = = -1) {
tartgetArr = str.slice(0, donum)
floatstr = str.slice(donum, len)
} else {
tartgetArr = str.slice()
}
// Process the integer part
let tartlen = tartgetArr.length;
if (tartlen == 3) {
return tartgetArr + floatstr
} else {
if (tartlen % 3= = =0) {
return tartgetArr.match(/\d{3}/g).join(', ') + floatstr
} else {
return tartgetArr.slice(0,tartlen % 3) +', '+tartgetArr.slice(tartlen % 3,tartlen).match(/\d{3}/g).join(', ') + floatstr
}
}
}
console.log(format('1231231.123'))
Copy the code