In the following process, there is no problem when the number 9999 is entered.
However, when entered as 9,999, the result is NaN.
How do I make an edit? I need to be able to use comic numbers.
I take the percentage of the number entered in input and print it to the input below.
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="" />
You need to parse the input value as float if you want to accept comma-values, otherwise it will be text and you can not calculate with text-values :)
If the numbers will only be full numbers and you want to strip out a thousand seperator a parseInt should do the job, otherwise you could replace all non-number characters, or better use an input type="number"
to only allow the input of numbers
parseFloat see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
input type number see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number
Comma-separated numbers is a String
not a Number
in Javascript.
So you can't count a String
with Number
, there is why you got a NaN
.
There are many ways can achieve what you want, but the important thing is that don't use a String to count a Number.
In my view, you can use the replace()
to remove the comma from your input value, and then use parseInt()
to get an correct number. Like this :
var num1 = document.getElementById("firstNumber").value;
num1 = parseFloat(num1);
Remove comma when calculating result:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.