Here is my really basic Javascript calculator code. Except for the addition symbol, my calculator is just working fine. However, addition is not doing its job: instead it combines them. How to fix it?
var first = prompt("First number");
var second = prompt("Second number");
parseInt(first);
parseInt(second);
var islem = prompt("Is it +/-/* or /?");
if (islem == "+" ) {
document.write(first + second);
}
else if ( islem == "-") {
document.write(first - second);
}
else if ( islem == "*" ) {
document.write(first * second);
}
else {
document.write(first / second);
}
The parseInt() function parses a string argument and returns an integer.
You have to assign parsed value to your variable, like this:
first=parseInt(first);
second=parseInt(second);
Or simply,
document.write(parseInt(first)+parseInt(second));
See reference here.
var first = prompt("First number");
var second = prompt("Second number");
parseInt(first);
parseInt(second);
var islem = prompt("Is it +/-/* or /?");
if (islem == "+" ) {
document.write(parseInt(first)+parseInt(second));
}
else if ( islem == "-") {
document.write(first-second);
}
else if ( islem == "*" ) {
document.write(first*second);
}
else {
document.write(first/second);
}
When you use parseInt(), you need to capture the returned value so that you can use that number going forward. Right now, you are calling parseInt() and not doing anything with the returned value, so it is lost immediately.
It is also advisable to use the optional second parameter to parseInt(), which is the radix value that sets the base of the number you are working with. Typically, you'll want that to be 10 when working with base 10 numbers. This is really important because if the string you are working with starts with a 0 and you don't supply the radix, the operation will assume you are working with an octal value and if the string were to start with 0x, then the operation will assume you are working with a hex (base 16) value.
See more about using parseInt().
The code should be:
var first = prompt("First number");
var second = prompt("Second number");
first = parseInt(first, 10);
second = parseInt(second, 10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With