代码之家  ›  专栏  ›  技术社区  ›  starter_id

Javascript函数(ASP.net)上使用句点的千位分隔符

  •  1
  • starter_id  · 技术社区  · 9 年前

    对不起,如果重复了,但我真的很困惑这些javascript。 如果愿意,请帮助我。

    我有一个已经运行的javascript函数,该函数将添加带逗号的千位分隔符:

    function addCommas(x) {
      //remove commas
      retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;
    
      //apply formatting
      return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."); 
    }
    

    我在文本框中调用这个函数,如下所示:

     Number Format <asp:TextBox ID="txtPrice" runat="server" onkeyup="this.value=addCommas(this.value);"></asp:TextBox>
    

    输出如下(使用逗号分隔):

    60,000,234

    但是我想要输出,看起来像这样(分隔符使用句点):

    60.000.234

    请给我一个仍然使用这些Javascript函数的解决方案。谢谢

    2 回复  |  直到 9 年前
        1
  •  4
  •   nelek    9 年前

    我在评论中注意到我的代码中有什么错误。

    试试这个,我很久以前就用过了。

    function addCommas(x) {
     var retVal=x.toString().replace(/[^\d]/g,'');
      while(/(\d+)(\d{3})/.test(retVal)) {
       retVal=retVal.replace(/(\d+)(\d{3})/,'$1'+'.'+'$2');
     }
     return retVal;
    }
    Number <input type="text" onkeypress="this.value=addCommas(this.value);" onkeyup="this.value=addCommas(this.value);" />

    我希望这对你有帮助。

        2
  •  0
  •   Ikechi Michael    9 年前
    function addCommas(x) {
        x = '' + x;
        //remove commas
        retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;
        //apply formatting
        return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."); 
    }
    

    它仍然是您的函数,但变量x首先被转换为字符串。