Home>

When formatting values,A common problem is formatting in thousandths,There have been many solutions to this problem online.You can also use the array.prototype.reduce method to implement 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], //sign bit
    integers=(groups [2] || "") .split (""), //integer part
    decimal=groups [3] || "", //decimal 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 under ie9.However, we can implement a reduce method based on ecmascript 3.

In JavaScript, the match pattern parameter of the replace method of a string can be a regular expression in addition to the string.The following is the specific code that uses the string.prototype.replace method to implement the thousandth formatting:

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,You can use $1 to backreference,?= (\ d {3}) + (?:$| \.) Is a forward assertion,Indicates that matching 1 to 3 digits must be followed by 3 digits, but not including the last 3 digits or 3 digits and decimal points.

  • Previous Detailed explanation of the basic principles of Android custom controls (1)
  • Next JQuery proxy to implement the proxy method