0

Calculation

I am trying to add totalAmount + tipAmount, but the code is treating the variables as a string rather than as a numerical value. How would I correct this? Ie: 100 + 20 currently = 10020, but I want it to show 120 var totalAmount = prompt ("Enter total amount billed") var tipAmount = prompt ("Enter tip amount") document.write (totalAmount + tipAmount);

7th Nov 2019, 8:35 AM
Alex
Alex - avatar
3 Respostas
+ 5
A. Quick answer parseInt(var) or parseFloat(var) or Number(var) B. demo https://code.sololearn.com/WhheW2KGJl8F/?ref=app C. Explanation the + operator can be Number.addition or String.concantenation. D. There is a difference between parseInt and Number, read: https://www.sololearn.com/post/115762/?ref=app https://code.sololearn.com/WKKkpq0efxai/?ref=app
7th Nov 2019, 8:40 AM
Gordon
Gordon - avatar
+ 9
Here in this case, you can use parseInt which is an inbuilt function in JavaScript which converts a String into an integer value. You can read here more about it : https://www.geeksforgeeks.org/javascript-parseint-with-examples/ After taking prompt input you can convert it into integer as it take integer input. totalAmount = parseInt(totalAmount); Same applies for tipAmount.
7th Nov 2019, 8:41 AM
Nova
Nova - avatar
+ 1
thank you!
7th Nov 2019, 8:47 AM
Alex
Alex - avatar