javascript - I keep getting NaN and i can't find out how to fix it -


it happens when gets cost2. think problem might in trying define price2, else works fine. i'm new javascript i'm sure it's simple mistake, great!

<html>     <body>         <h1>gas mileage</h1><br></br>     </body>     <script type="text/javascript">         var mpg, price1, distance, gallons, cost1, price2, cost2;          mpg = prompt("enter car's miles per gallon");         document.write("your car gets "+mpg+" miles per gallon.");         document.write("<br>");          price1 = prompt("enter current cost of gas");         document.write("gas costs $"+price1+" per gallon.");         document.write("<br>");          distance = prompt("enter amount of miles travel");         gallons = distance/mpg;         cost1 = gallons*price1;         document.write("to travel "+distance+" miles, cost $"+cost1);         document.write("<br>");          price2 = (0.1+price1);         cost2 = gallons*price2;         document.write("but if gas cost 10 cents more per gallon, cost $"+cost2);      </script> </html> 

prompt returns string.

if want use input in calculations, you're going have use parseint or parsefloat:

var answer1 = parseint(prompt("question 1")); var answer2 = parsefloat(prompt("question 2")); 

that said, division , multiplication operators coerce it's parameters numbers.

the problem occurs when coercion doesn't work: price2 = (0.1+price1);
there, because + concatenate 2 parameters string, price2 can string "0.11.54" if price1 "1.54".
trying multiply number invalid number results in nan.

converting user input string number solves issue, since + can add 2 numbers together, instead of concatenating them.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -