# Is there a way to force JavaScript to return a negative value in an alert box? [duplicate]

• A+
Category：Languages

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'); } ``

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();``