Javascript Either Parseint Or + , Appending Instead Of Adding
Solution 1:
parseInt(a = prompt('Pay 1'), 10);
...
parseInt(b = prompt('Pay 2'), 10);
...
parseInt(t = (a * 20 + b), 10);
Here a
, b
and t
, all have got string data only and when it is converted to an int, its discarded immediately. So, fix them like this
a = parseInt(prompt('Pay 1'), 10);
...
b = parseInt(prompt('Pay 2'), 10);
...
t = a * 20 + b;
According to ECMA Script's specifications for Additive operation,
7 If Type(lprim) is String or Type(rprim) is String, then Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
So when you use a string and number with +
operator, result will be concatenation of both the operands.
According to ECMA Script's specifications for Multiplicative operation,
- Let left be the result of evaluating MultiplicativeExpression.
- Let leftValue be GetValue(left).
- Let right be the result of evaluating UnaryExpression.
- Let rightValue be GetValue(right).
- Let leftNum be ToNumber(leftValue).
- Let rightNum be ToNumber(rightValue).
*
operator basically converts both the operands to numbers. So, the result will be proper even if both the operands are numbers in strings.
You can confirm the above mentioned things with this
var a = "100", b = "12";
console.log(a * 20); // Prints 2000, both operands are converted to numbersconsole.log(a * 20 + b); // Prints 200012, as b is string, both are concatenated
Solution 2:
I'm not a Javascript expert by any means, but you seem to be ignoring the result of parseInt
, instead storing just the result of prompt()
in your a
, b
and t
variables. I'd expect this:
parseInt(a = prompt('Pay 1'), 10);
to be:
a = parseInt(prompt('Pay 1'), 10);
(And the same for the other prompts.)
At that point, the variables' values will be the numbers rather than the strings, so +
should add them appropriately.
Solution 3:
You parsing result which is already wrong due to appending as string:
try updating following statements:
a = parseInt(prompt('Pay 1'), 10);b = parseInt(prompt('Pay 2'), 10);t = a * 20 + b; // no need to parse as a and b already integers
Solution 4:
parseInt()
returns an integer value. And you dony need parseInt(string, 10)
, for parseInt
decimal system used by defaults.
a = parseInt(prompt('Pay 1'));b = parseInt(prompt('Pay 2'));t = a * 20 + b;
Solution 5:
try
a = parseInt(prompt('pay 1'),10);
etc. for b and t.
Now you declare a as prompt('pay 1')
and not as the int value returned by parseInt
.
Post a Comment for "Javascript Either Parseint Or + , Appending Instead Of Adding"