search

Home  >  Q&A  >  body text

javascript - Regular expression /(\d)(?=(\d{3})+\.)/g

How to add a comma to every three digits of the number to the left of a floating point number, such as converting 12000000.11 into "12,000,000.11"?

function commafy(num){

  return num && num
      .toString()
      .replace(/(\d)(?=(\d{3})+\.)/g, function(, ){
          return  + ',';
      });

}
I don’t know how to understand this regular rule. /(d)(?=(d{3}) .)/g
Not sure how it works

伊谢尔伦伊谢尔伦2803 days ago725

reply all(1)I'll reply

  • 阿神

    阿神2017-05-19 10:37:23

    Match/(d)(?=(d{3})+.)/gThe number is followed by three digits or a multiple of 3, followed by a decimal point. d{3})+ means a number that is a multiple of 3, such as 3 numbers, 6 numbers, etc., ?= means that the following number must be a multiple of 3

    reply
    0
  • Cancelreply