i'm having some trouble with the parseInt function or + operand. I want to take in two numbers, multiply one by a third number and add them together. Instead of adding the numbers it appends one number to another.
<script language = 'JavaScript'>
function calculate_total()
{
var a = 0;
var b = 0;
var t = 0;
parseInt(a = prompt('Pay 1'), 10);
//Input of 10
if(isNaN(a))
{
alert('Error A');
}
//No Error
parseInt(b = prompt('Pay 2'), 10);
//input of 12
if(isNaN(b))
{
alert('Error B');
}
//No Error
parseInt(t = (a * 20 + b), 10);
if(isNaN(t))
{
alert('Error T');
}
else
{
alert('Total Pay: ' + t);
//expected answer 212
//Actual Answer 20012
}
//No Error
}
calculate_total();
</script>
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.
See more on this question at Stackoverflow