When I run this function with the first radio button selected, the system outputs the correct value of 30. However, once I try to apply some changes to this value (for example by adding 1 to this value of 30) the system shows me 301 as a result.
I get the same issue when the radio button with value 25 is selected. Once I try to do mathematical changes, the system treats this variable as 250.
Any ideas what I am missing here? Thanks in advance.
<script>
function f1()
{
...
var Ergebnis_RP = document.getElementsByName("Ergebnis_RP");
if(Ergebnis_RP[0].checked)
{ var Erg = Ergebnis_RP[0].value;}
else if(Ergebnis_RP[1].checked)
{ var Erg = Ergebnis_RP[1].value;}
...
document.write(Erg);
var Spielwert = Erg + 1;
document.write(Spielwert);
}
</script>
<body>
<input type="radio" name="Ergebnis_RP" value=30>Verl. Schwarz
<input type="radio" name="Ergebnis_RP" value=25>Verl. U3
</body>
The value of a textbox is always a string. You need to coerce it to a number. The easiest way to do that is:
+Ergebnis_RP[0].value
Be sure to do this every time you read a number from a textbox.
Further explanation of the issue:
When you combine two strings, they are concatenated like "ab" + "cd" -> "abcd".
But when you combine different types, the second one is coerced to be the same as the first. "ab" + 1 -> "ab" + "1" -> "ab1".
Your code takes a string and adds a number. The string happens to be digits but that doesn't matter. "12" + 3 -> "12" + "3" -> "123".
To fix this, start with a number then add the string. 0 + "12" -> 0 + 12 -> 12.
As a shortcut, the + operator acts on numbers just like the - operator. Consider the number -5. The - is a negation. + is another unary operator that takes a number and returns the same number. Sounds useless, but it has its place. +"12" -> 12.
Related
var fir=prompt("Enter first Number");
var sec=prompt("Enter second number");
var sum=Number(fir)+Number(sec);
alert("The sum is " + sum);
alert("The difference is " + fir-sec);
alert("The product is " + fir*sec);
alert("The division is " + fir/sec);
Now: suppose fir=2 and sec=1.
The output is:
3
NaN
2
2
Why is the difference NaN instead of 1?
* and / have higher operator precedence than + and -, just like with PEMDAS order of operations in standard math. Specifically, + and - have precedence 13, whereas * and / have precedence 14.
When an expression has + and -s only, they're evaluated in left-to-right order. So, your code is equivalent to:
alert(("The Difference is " + fir) - sec);
alert("The product is " + (fir*sec));
alert("The division is " + (fir/sec));
In the second and third alert, fir and sec get combined into a single numeric expression before being concatenated with the prior string.
In the first alert, "The Difference is " + fir get put together first, resulting in another string (a string + a number results in another string). So then you have
alert((someString) - sec);
But someString - sec doesn't make sense - you can't subtract something from a string, so the expression resolves to NaN.
You can do one thing
var fir=prompt("ENter 1st Number");
var sec=prompt("Enter second number");
var sum=Number(fir)+Number(sec);
var sub=Number(fir)-Number(sec);
alert("The Sum is " + sum);
alert("The Difference is " + sub);
alert("The product is " + fir*sec);
alert("The division is " + fir/sec);
Usually, the plus operator + sums numbers.
But, if the binary + is applied to strings, it merges (concatenates) them:
let s = "my" + "string";
alert(s); // mystring
Note that if one of the operands is a string, the other one is converted to a string too.
For example:
alert( '1' + 2 ); // "12"
alert( 2 + '1' ); // "21"
See, it doesn’t matter whether the first operand is a string or the second one. The rule is simple: if either operand is a string, the other one is converted into a string as well.
However, note that operations run from left to right. If there are two numbers followed by a string, the numbers will be added before being converted to a string:
alert(2 + 2 + '1' ); // "41" and not "221"
String concatenation and conversion is a special feature of the binary plus +. Other arithmetic operators work only with numbers and always convert their operands to numbers.
For instance, subtraction and division:
alert( 2 - '1' ); // 1
alert( '6' / '2' ); // 3
reference https://javascript.info/operators
Because you're concatenating a string ("The difference is") with a number, obtaining a string, and then subtracting a number from it. Use parentheses
alert("The Difference is " + (fir-sec));
The problem you face is due to dynamic type conversion. In your second alert JS engine 1st concatenates "The Difference is " and fir and then subtracts sec. You have to add braces:
alert("The Difference is " + (fir-sec))
In all other cases it is ok because * and / operators have higher priority than + operator
Remeber Math's BODMAS theory,
in case of multiplication and division it works and giving you result.
But for substraction, it first does addition.
And finally:
String - Number = NaN
I'm looking for an alternative way to do an isNaN test
My original code looked like this. The code works, but I noticed that num1 changes type, which is ugly
// example 1: num1 changes type
num1 = parseInt(str1, 10);
if isNaN(num1){num1=-1;}
I changed it to this, but this one uses duplicate code
// example 2: duplicate code
if (isNaN(parseInt(str1,10))){num1=-1;}
else {num1=parseInt(str1,10);}
At first I was thinking about adding an extra variable to store parseInt(str1,10) but that variable will change type, too and is therefore in effect the same as example 1.
Is there an alternative to example 1 or 2?
by changes type I mean this
console.log(typeof(isNaN("123"))); // boolean
console.log(typeof(isNaN("abc"))); // boolean
console.log(typeof(parseInt("123", 10))); // number
console.log(typeof(parseInt("abc", 10))); // number
.
console.log(typeof(Number("123"))); // number
console.log(typeof(Number("abc"))); // number
console.log(Number("123")); // 123
console.log(Number("abc")); // NaN
First, I would suggest that parseInt() isn't the best choice. For example:
var x = parseInt("123hello world how are you today?", 10);
will set "x" to 123 and simply ignore the trailing garbage.
You could set up a functional way to do this, if you really wanted to avoid the intermediate temporary value:
function ifNumeric( s, f ) {
s = +s;
if (!isNaN(s)) f(s);
}
ifNumeric( someString, function( n ) { /* whatever, with "n" being a number */ } );
but that seems a little extreme. But anyway note that in that example the + operator is used to coerce the value of the variable to the "number" type. You could alternatively use the "Number" constructor, but not as a constructor:
var numeric = Number( someString );
Either of those will give you a NaN if the string isn't a completely valid number without trailing garbage.
edit — if you just want a safe "give me a number" converter:
function toNumber( value, ifGarbage ) {
value = +value;
return isNaN(value) ? ifGarbage : value;
}
var num1 = toNumber( str1, -1 );
What does the following evaluate to?
"1"+2+4
What about this:
5 + 4 + "3"
In the first case since "1" is a string, everything is a string, so the result is "124". In the second case, its 93.what is happening here? Why does addition happen in one instance, while string concatenation occurs in the other?
var x = "1" + 2 + 4;
var z = 5 + 4 + "3";
console.log(x); // "124"
console.log(z); // 93
Can anyone explain this?
expression evaluates from left to right.
"1"+2+3
^--^
"12" //string +3
^_____________^
"123" //string
in 2nd case
1+2+"3"
^_^
3+"3"
^___^
"33" // string
Think about the operation order (rtl or ltr) each time it performs a binary operation it converts it accordingly so 5+4 will be int and (5+4) + "3" will be a string because "3" is a string
Same method applies to different examples
var x = "1" + 2 + 4; // 124
This is taking the string "1" and concatenating to it "2" and "4" as strings.
var z = 5 + 4 + "3"; // 93
This is taking the numbers 4 and 5 and adding them together to get the number 9, and then concatenating the string "3" to that to produce another string.
The key thing to take away here is that the end result of what you're doing here is string concatenation. The order of evaluating the numbers is different but the end result is a string.
In the first case you create a string first (1) and then javascript concatenates the following number as strings (124).
In the second one you create a number first then javascript adds the second number to this first number (5 + 4 = 9) and then you add a string so it does the concatenation of 9 and 3
In both case apply the type conversion and left to right precedence.
in first one,
var x = "1" + 2 + 4; // 124
compiler take 1 as string and after that it will concatenating with 2 now 12 is the string so it will concatenate with 4 and result will produce "124" as string.
var z = 5 + 4 + "3"; // 93
in Second one,
first 5 and 4 is numeric so make addition and result will be 9. and this will concatenate with string 3 soo output will be 93 as string.
My first day of Javascript and I am incredibly confused. I am passing numbers returned from a form to a function, but the result is not consistent with what it should be. My testing leaves a lot to be desired, but hopefully the following makes sense.
The function g calculates the sum of the sequence.
<form name="gaussform">
<input name="min"
type="number"
min="1"
value="1">
<input name="max"
type="number"
min="2"
value="10">
<input name="step"
type="number"
min="1"
value="1">
<input onclick="alert_g()"
type="submit"
value="calculate">
</form>
<script type="text/javascript">
function g(min,max,step) {
var actualmax = max - ((max - min) % step)
return (min + actualmax) * ((1 + ((actualmax - min) / step)) / 2)
}
function alert_g() {
var frm = document.forms["gaussform"]
var min = frm["min"].value
var max = frm["max"].value
var step = frm["step"].value
if (min == 1) {
alert("min is 1")}
if (max == 10) {
alert("max is 10")}
if (step == 1) {
alert("step is 1")}
alert(g(min,max,step))
// below returns the desired result
alert(g(1,10,1))}
</script>
the if statements are only so I can understand what is going on!
So if the user enter 1,10,1 (the default values) the result should be 55.
alert(g(1,10,1)) -> 55
alert(g(min,max,step) -> 550
alert(g(1,100,2)) -> 2500
alert(g(min,max,step) -> 4975 (obviously min,max,step == 1,100,2)
the function g is correct, but I do not understand what is happening to the values that are being passed to it.
This expression...
min + actualmax
...is the problem.
You probably want to make that...
+min + +actualmax
...or use parseFloat(), parseInt() or whatever suits your requirements to turn those strings into an actual Number.
jsFiddle.
JavaScript's + operator is overloaded for arithmetic addition and string concatenation. Because user input is always a string, you're doing string concatenation.
The values you use in your function are strings (every value returned by a form will be a string). You need to convert them to number to get the good result. This can be done with parseFloat function.
parseFloat('5') // return 5
parseInt can also be used if you want an Integer (no floating point number e.g.: 1.3), but be sure to set the radix parameter in order to always get consistent results.
parseInt('5', 10) // return 5
This can be confusing because Javascript use the + symbol for addition and concatenations of strings (which is . sign in PHP for example). As so, it's hard for the javascript engine to know how a value is expected to be converted.
By the way, you can always use typeof operator to checkout the type of a variable. For example:
typeof '5' // ouput: String
typeof 5 // output: Number
alert(g(parseInt(min),parseInt(max),parseInt(step))) has solved it!
But apparently this is bad form. See comments...
alert(g(parseInt(min,10),parseInt(max,10),parseInt(step,10))) perhaps?
I'm using jQuery to retrieve a value submitted by an input button. The value is supposed to be an integer. I want to increment it by one and display it.
// Getting immediate Voting Count down button id
var countUp = $(this).closest('li').find('div > input.green').attr('id');
var count = $("#"+countUp).val() + 1;
alert (count);
The above code gives me a concatenated string. Say for instance the value is 3. I want to get 4 as the output, but the code produces 31.
How can I change an HTML input value's data type to integer?
To convert strValue into an integer, either use:
parseInt(strValue, 10);
or the unary + operator.
+strValue
Note the radix parameter to parseInt because a leading 0 would cause parseInt to assume that the input was in octal, and an input of 010 would give the value of 8 instead of 10
parseInt( $("#"+countUp).val() , 10 )
Use parseInt as in: var count = parseInt($("#"+countUp).val(), 10) + 1; or the + operator as in var count = +$("#"+countUp).val() + 1;
There is a parseInt method for that or Number constructor.
var count = parseInt(countUp, 10) + 1;
See w3schools webpage for parseInt.