Commonly used js such as the thousand-digit count displayed by the amount

function f(s, n) {
    // Reserve up to 20 decimal places
    n = n > 0 && n <= 20 ? n : 2;
 
    // The meaning of +'' here is to convert the number into a string, and \. \- in the regular expression means the decimal point and negative sign
    // delete characters that are not decimal points or minus signs in s
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
 
    // split('.') uses the decimal point to split the number into integer part and fractional part
    // l is the left part of the floating point number, which is the integer part, and r is the fractional part
    // eg s = -123456.789; s.split('.') => ['-123456', '789']
    // split('') splits the string into an array of single characters
    // '-123456.789'.split('.')[0].split('') => ['-','1','2','3','4','5','6']
    // .reverse() reverse the order ['-','1','2','3','4','5','6'].reverse() => ['6','5 ','4','3','2','1','-']
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1]; // '789'
 
    // .indexOf() determines whether the string contains a certain string, if not, returns -1
    // Here, it is judged whether there is a negative sign in the number. If there is a negative sign, it means that the length of the integer part of the number should be reduced by one
    // the above example l.length = 7 but there is a negative sign so len = 6
    var len = (s.indexOf("-")!= -1) ? l.length - 1 : l.length;
 
    t = "";
    //
    for (i = 0; i < len; i++)
    {
        // l = ['6','5','4','3','2','1','-']
        // Here, the position of inserting the comma is judged by doing the remainder operation on i + 1
        // (i + 1) % 3 == 0 inserts a comma every three digits
        // (i + 1) != len No comma at the beginning of the number
        // result: t = '654,321'
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != len ? "," : ""); //I don't understand it and give these two conditions example
 
    }
 
    // If there is a negative sign, add a negative sign at the beginning
    // then reverse the order back and concatenate the fractional part back
    // '-123,456.789'
    return ((s.indexOf("-")!= -1) ? "-" : "") + t.split("").reverse().join("") + "." + r; / /This return is an example, I don't understand
 
}

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326683890&siteId=291194637