var tt = gas+0.1
document.write (vartt);
Duplicate
var tt = gas+0.1
document.write (vartt);
Duplicate
You could make use of Number function too.
var tt = Number(gas) + 0.1;
document.write(tt);
The user entered a string. If you want to do arithmetic with it instead of string concatenation, you must convert to a number. There are many different ways to do that including parseInt(gas, 10)
, parseFloat(gas)
, Number(gas)
and +gas
:
Here's one implementation:
var tt = parseFloat(gas) + 0.1;
document.write(tt);
Also, your document.write()
statement was not correct either. The variable name is just tt
, not vartt
.
Unless you are using <input type="number" />
for the input, the user provided data will be a string. By default, when you try to add a string + a number it will cast that number to a string. You can do what Видул Петров suggested and add the unary +
to gas
to force cast it to a number, however if it's still a string that can't be cast to a number (like someone entering in the word 'five' vs '5'), youll get NaN
as a result unless you have the proper control over the incoming data.