<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var number=prompt("nb","nbpl?");
if (number!=0)
{
x=number+2;
document.getElementById("demo").innerHTML=x;
}
}
</script>
</body>
</html>
It works with: number/2, number*2, number-2, but just not with number+2.
Please, any hints how to solve the problem?
Many thanks!
The problem arises from the dual nature of the + operator used for both numeric addition and string concatenation. If both operands are numbers to start with will the + operator performs addition otherwise it converts all of its operands to strings and does concatenation.
Therefore 2 + 2 = 22
Convert the string to a number with parseInt (for integers) or ParseFloat (for floating point numbers).
In addition to what Paul says, note that the parseInt function takes an optional second parameter (radix) that specifies which numeral system is to be used.
For example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with “0x”, the radix is 16 (hexadecimal)
If the string begins with “0”, the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)[/QUOTE]
If your string is already in the form of a number, it might be better to use Number() which converts the object argument to a number that represents the object’s value.
If the value cannot be converted to a legal number, NaN is returned.
The correct JavaScript function for converting a string to a number is
num = Number(str)
or you can use the short version
num = (+str)
note that to use the short version you must wrap the parentheses around the + and the string so that it operates as a unary + - which always converts to a number).
Please, how to get each result in other line? LIke:
10
2
p.s. I tried with \ and with <br> but no result…
Code is here:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var nr=prompt("Please enter number","number1");
var nr2=prompt("Please enter number","number2");
x=parseInt(nr)+parseInt(nr2)+nr-nr2;
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>