【问题标题】:Thousands separator using Period on Javascript Function (ASP.net)在 Javascript 函数 (ASP.net) 上使用句点的千位分隔符
【发布时间】:2016-03-06 06:47:26
【问题描述】:

对不起,如果重复,但我真的对这些 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 函数的解决方案。谢谢

【问题讨论】:

  • 试试这个:function addCommas(x) {var retVal= x.toString().replace(/[^\d]/g, '').replace(/(.{3})/g,'$1.'); return retVal;} ...它将忽略除数字之外的所有内容,并且每第三个位置插入一个点。当然,像 onkeyup 在你的 textbox 中也添加 onkeypress
  • @nelek 但是当字符到达字符串句点 (.) - 该函数忽略我按退格键。而且句号不正确,例如我输入数字“60000234”的8个字符时,它将变成“600.002.34”。

标签: javascript asp.net string-formatting separator onkeyup


【解决方案1】:

我在评论中注意到我的代码有什么问题。

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

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 &lt;input type="text" onkeypress="this.value=addCommas(this.value);" onkeyup="this.value=addCommas(this.value);" /&gt;

我希望这会对你有所帮助。

【讨论】:

    【解决方案2】:
    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 先转换成字符串。

    【讨论】:

      猜你喜欢
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 2013-09-02
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多