Regex for positive lookahead thousand separator that would not mach numbers after dot

前端 未结 1 1450
我寻月下人不归
我寻月下人不归 2021-01-22 18:08

I am using following regex to \'insert\' commas into numbers in javascript.

(\\d)(?=(\\d{3})+(?!\\d))

It works very well with integers however

相关标签:
1条回答
  • 2021-01-22 18:51

    You can achieve this only in 3 steps:

    1. Split the number into integer and decimal parts
    2. Modify the integer part
    3. Join.

    There is no variable-width look-behind in JS that would be very handy here.

    var s = ".12345680000454554";
    //Beforehand, perhaps, it is a good idea to check if the number has a decimal part
    if (s.indexOf(".") > -1) { 
        var splts = s.split(".");
        //alert(splts);
        splts[0] = splts[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
        //alert(splts[0]);
        s = splts.join(".");
        alert(s);
      }
    else
      {
         alert(s.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'));
      }

    0 讨论(0)
提交回复
热议问题