[英]add a thousand separator to a paragraph from an input tag
我有一個進行計算的輸入標簽,但我想獲取輸入標簽的值並將其解析為段落標簽並對其進行格式化。 這是輸入標簽
<form:input id="amount" min="1" class="form-control"
type="number" required="true"
placeholder="Enter Value"></form:input>
這是用於格式化上面輸入的值的段落標記
<p>Inputted Amount: </p>
我已經研究過並且有這個但不知道如何將它傳遞給段落標簽:
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;
}
您可以使用 Intl.NumberFormat 格式化數字:
請參閱我為您創建的這個codepen 。
示例代碼:
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:
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();
請參閱: 國際數字格式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.