A perennial interview question,
Var num = 1234567890.12345;Copy the code
I believe that you have written front-end code for so long, whether it is training or interview, this kind of question occurs frequently,
There are many ways to do this online, but I’m going to give you two simple ways to do it
1.toLocalString()
letnewNum = num.toLocalString(); /* * => 1,234,567,890.12345 * the fastest way to cheat */Copy the code
So let’s take a look at this method, and MDN says,
/* * toLocaleString() returns a string representing the elements in the array. * The elements in the array will be converted to strings using their respective toLocaleString methods, and * these strings will use a locale-specific string (such as a comma)","Separated). * /Copy the code
This is cheating lawlessness!
2. Let’s look at my low method
function changeNum(num) {
if(typeof num ! = ='number') {
throw new Error('Please pass in a number');
return false; } // Cut the decimal point num = num +' ';
let index = 0,i = 0 ;
for(; i < num.length ; i++) {if(num[i] === '. ') { index = i; }} // Startletstart = num.slice(0,index) ; / / endlet end = num.slice(index,-1) ;
let reson = [];
// console.log(start.length)
let firstStart = ' ',j = start.length; // Determine if the value is a multiple of three digits // the first digitlet newStart = start.slice(0,j % 3) ;
console.log(newStart,start)
start = start.replace(newStart,' ');
// Math.floor(j % 3) === j % 3 ?
for(; j >= 0 ; J --){// console.log(j) // iterate over the items that matchif( j % 3 === 0 && j ! == start.length) { console.log(j,'123') reson.push(j)}} // Stores the cut stringletsliceStr = []; // Reverse array reson = reson.reverse(); // Iterate over the coincidence cut arrayfor(letk = 0 ; k < reson.length ; K ++) {console.log(reson[k],reson[k+1]) slicestr.push (start.slice(reson[k],reson[k+1]))} // Returns a new arraylet newNum = ' ';
if(newStart) {
newNum = newStart + ', ' + sliceStr.join(', ') + end;
}else {
newNum = sliceStr.join(', ') + end;
}
return newNum
}
let str = changeNum(num);Copy the code
The amount of code is a bit scary…. Let’s look at the concrete idea
/* 1 => first convert the numeric type to a string, use indexof to index whether there is a decimal point 2 => cut the start string and end string with a decimal point 3 => mod start, store the remainder with newStart, And delete the corresponding owned in the start string. 5 => Array inversion (redundant operation... J++ will do...) Cut the string 6 => Check whether the remainder exists and return different values */Copy the code
Finished writing, wow suddenly cried out…
After still want more in-depth understanding js ah, know of too shallow…
Make a little progress with everyone every day