0
var tt = gas+0.1
document.write (vartt);

Duplicate

Godwin
  • 54
  • 2
  • 9
  • There are [*many duplicates*](http://stackoverflow.com/search?q=%22%5Bjavascript%5D+concatenate+not+add). – RobG Sep 20 '15 at 22:40

3 Answers3

2

You could make use of Number function too.

var tt = Number(gas) + 0.1;
document.write(tt);
0

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

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.

James LeClair
  • 1,234
  • 10
  • 12