[英]Comma-separated numbers in input in Javascript
在以下過程中,輸入數字9999不會有問題。
但是,當輸入為9,999時,結果為NaN。
如何進行編輯? 我需要能夠使用漫畫號。
我將輸入中所輸入數字的百分比打印到下面的輸入中。
function yirmibes() { num1 = document.getElementById("firstNumber").value; document.getElementById("result").value = (num1 / 100) * 25; } function elli() { num1 = document.getElementById("firstNumber").value; document.getElementById("result").value = (num1 / 100) * 50; } function format(input) { var nStr = input.value + ''; nStr = nStr.replace(/\\,/g, ""); 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'); } input.value = x1 + x2; }
Number: <input type="text" id="firstNumber" onkeyup="format(this)" /> <br/><br/> <input type="button" onClick="yirmibes()" Value="25%" /> <input type="button" onClick="elli()" Value="50%" /> <br/><br /> The Result is : <input type="text" id="result" Value="" />
如果要接受逗號值,則需要將輸入值解析為float,否則將是文本,並且無法使用text-values進行計算:)
如果數字只能是整數,並且您想去除一千個分隔符,則parseInt應該可以完成此工作,否則您可以替換所有非數字字符,或者最好使用input type="number"
僅允許輸入數字
parseFloat參見: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
輸入類型編號,請參閱: https : //developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number
逗號分隔的數字是String
而不是Javascript中的Number
。
所以你不能用Number
來計數一個String
,這就是為什么你得到一個NaN
。
有很多方法可以實現您想要的,但是重要的是不要使用字符串來計算數字。
在我看來,您可以使用replace()
從輸入值中刪除逗號,然后使用parseInt()
獲取正確的數字。 像這樣 :
var num1 = document.getElementById("firstNumber").value;
num1 = parseFloat(num1);
計算結果時刪除逗號:
function yirmibes()
{
num1 = document.getElementById("firstNumber").value.replace(',', '');
document.getElementById("result").value = (num1 / 100) * 25;
}
function elli()
{
num1 = document.getElementById("firstNumber").value.replace(',', '');
document.getElementById("result").value = (num1 / 100) * 50;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.