8

JavaScript is returning X - Y , where X and Y are Real numbers and their sum is negative, instead of just the negative sum.

I've tried an if else statement using

if (Math.sign(function)<0)
else

where the if statement just had a "-" in front of the value to concatenate the string "minus" character in front of the number and the else statement was just a regular print out

function velocity_final(initial_velocity, acceleration, time)
{
    var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
    var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
    var time = prompt('Please enter the time in seconds');
    var final_velocity = initial_velocity + acceleration * time;
    alert('The Final Velocity is '+ final_velocity  + ' Meters Per Second');
}
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • for the prompts I put in 32, -9.81, 10 and it returns 32-98.100000 instead of just a negative number – Evan Howington Dec 20 '18 at 03:51
  • 1
    Please do take the time to format your sample code and you do not have to follow up content on a comment, edit the post instead. You get unlimited edits on your post so feel free to use as much as you want. – Abana Clara Dec 20 '18 at 03:53
  • it would be hilarious if JavaScript actually parsed any potential negative numbers in alerts and removed them – sudo rm -rf slash Dec 20 '18 at 08:00

3 Answers3

7

prompt always returns a string, not a number. Even if the person enters a number, it will be a string that represents that number, not a number itself.

You will need to cast the results of prompt to a number before you can preform addition on it. When used with string, + is the concatenation operator, rather then the addition operator.

Somewhat confusingly, you can actually use an unary + for this purpose.

var initial_velocity = +prompt('Please enter the Initial Velocity in Meters per Second');
var acceleration = +prompt('Please enter the acceleration in Meters per Second Squared');
var time = +prompt('Please enter the time in seconds');
var final_velocity = initial_velocity + acceleration * time;
alert('The Final Velocity is '+ final_velocity  + ' Meters Per Second');
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
2

The + operator can be both addition and string concatenation. When the prompt box returns, it gives you back a string. String + number = string, so it concatenates (joins) the two values together instead of adding them. To fix this, you can convert the string to a number using a single + operator (and some parentheses if you want) to convert the string to a number, like so:

function velocity_final()
{
    var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
    var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
    var time = prompt('Please enter the time in seconds');
    var final_velocity = (+initial_velocity) + (+acceleration) * (+time);
    alert('The Final Velocity is '+ final_velocity  + ' Meters Per Second');
}

console.log(velocity_final());

You could also convert the values as soon as the prompt returns a value, if you wanted.

PS: I removed the function parameters, as you set them manually anyways rather than passing anything in. If you do end up passing in values later rather than asking the user for them, you'll need to add those back into the function statement for them to be properly passed in.

Feathercrown
  • 2,547
  • 1
  • 16
  • 30
1

Prompt returns a string. Such that doing "1" +"-1" will result to "1-1" due to concatenation. Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers, if the evaluated strings contains a character, it gets concatenated instead. You need to explicitly cast the numbers.

You can use Number(), you can multiply each string to 1 to automatically convert them, you can use parseInt(), or you can use + preceding the returned values as shown by the other answers here. I would use the first one I mentioned in the example below.

function velocity_final()
{
    var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
    var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
    var time = prompt('Please enter the time in seconds');
    var final_velocity = Number(initial_velocity) + Number(acceleration) * Number(time);
    alert('The Final Velocity is '+ final_velocity  + ' Meters Per Second');
}

velocity_final();
Abana Clara
  • 4,602
  • 3
  • 18
  • 31
  • All good answers. Thank you for showing the Number part in the code. I had changed it to initial_velocity - ((-1)*acceleration*time) and that worked.. I changed to that because one of my other equations is almost identical except it utilizes subtraction and there were no issues. Previously I was just performing multiplication and division so this did not arise. I am converting my code from Python to JS, so I am learning on the fly. Thank you very much! – Evan Howington Dec 20 '18 at 04:27
  • Every time I've tested it (which, admittedly, was a few versions ago), implicit casting has always been faster than explicit casting, for some reason. Of course, performance may not matter in this case, and you can call this more readable. But I tend to use `a - -b` to add strings as numbers. – trlkly Dec 20 '18 at 06:11
  • 1
    `"1" + "1"` doesn't give `2`, it gives `"11"`. String concatenation always happens if one of the operands is a string (see step 7 in [the addition operator evaluation](https://www.ecma-international.org/ecma-262/8.0/#sec-addition-operator-plus)) – Birjolaxew Dec 20 '18 at 08:05
  • @Birjolaxew is absolutely correct, the sentence "*Why "1" + "1" becomes 2 in the printed output is because of how Javascript automatically attempts to parse strings into numbers*" does not reflect reality and is actually contradicting what you said before: `"1" + "-1"` does **not** get parsed, even though according to the quote it **should**. There is no logical reason for `"1" + "-1"` and `"1" + "1"` to produce two different *types* of results. It should be either treated as numeric in both cases or strings in both cases. – VLAZ Dec 20 '18 at 08:19
  • The statement following the quote "*if the evaluated strings contains a character, it gets concatenated instead.*" is *correct* but I think you are misunderstanding the actual meaning. The result would be concatenation if *any* of the actual variables is a string - `typeof someVar //"string"` and **not** if the *content* of the variable can be parsed as numeric - `someVar = "1"`. Also, another misconception here is that you consider `-` to be a "character" when `"-1"` is a string that can perfectly validly be parsed into a numeric and JS would tell you as much through `Number()`. – VLAZ Dec 20 '18 at 08:24