简体   繁体   English

从输入标签向段落添加千位分隔符

[英]add a thousand separator to a paragraph from an input tag

I have an input tag that does calculation, but I want to get the value of the input tag and parse it to a paragraph tag and format it.我有一个进行计算的输入标签,但我想获取输入标签的值并将其解析为段落标签并对其进行格式化。 Here is the input tag这是输入标签

<form:input id="amount" min="1" class="form-control"
                                                        type="number"  required="true"
                                                        placeholder="Enter Value"></form:input>

This is paragraph tag to format the value inputed above这是用于格式化上面输入的值的段落标记

<p>Inputted Amount: </p>

I have researched and have this but do not know how to pass it to the paragraph tag:我已经研究过并且有这个但不知道如何将它传递给段落标签:

function addSeperator(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

You can use Intl.NumberFormat to format a number:您可以使用 Intl.NumberFormat 格式化数字:

See this codepen I created for you.请参阅我为您创建的这个codepen

Sample Code:示例代码:

  Input:
  <input 
      id="amount" 
      min="1" 
      class="form-control"                          
      type="number"  
      required="true"
      value="87654321"
      onchange="showNumber()"
      onkeyup="showNumber()"
      placeholder="Enter Value"></input>

  <p>Inputted Amount: <span id="result"></span></p>

js: js:

function showNumber() {
  var n = document.querySelectorAll('#amount')[0].value;
  var formatter = new Intl.NumberFormat('de-DE', {});
  document.querySelectorAll('#result')[0].innerText = formatter.format(n);
  // → 87.654.321
}

showNumber();

See: Intl.NumberFormat请参阅: 国际数字格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM