Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force JS to do math instead of putting two strings together [duplicate]

I need javascript to add 5 to an integer variable, but instead it treats the variable as a string, so it write out the variable, then add 5 onto the end of the "string". How can I force it to do math instead?

var dots = document.getElementById("txt").value; // 5 function increase(){     dots = dots + 5; } 

Output: 55

How can I force it to output 10?

like image 902
Sean Avatar asked Jan 30 '11 05:01

Sean


People also ask

Why is my JavaScript concatenating instead of adding?

JavaScript (+) sign concatenates instead of giving sum? The + sign concatenates because you haven't used parseInt(). The values from the textbox are string values, therefore you need to use parseInt() to parse the value.

How do I sum two strings in JavaScript?

Use the addition (+) operator, e.g. Number('1') + Number('2') . The addition operator will return the sum of the numbers.

How do you sum two variables in JavaScript?

Basic JavaScript Addition The following code adds two numbers and stores the result in a variable named "sum": var x = 1; var y = 2; var result = x + y; The result is "3" in this simple example. Add numbers in JavaScript by placing a plus sign between them.


2 Answers

You have the line

dots = document.getElementById("txt").value; 

in your file, this will set dots to be a string because the contents of txt is not restricted to a number.

to convert it to an int change the line to:

dots = parseInt(document.getElementById("txt").value, 10); 

Note: The 10 here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.

like image 167
Alex Avatar answered Nov 07 '22 15:11

Alex


the simplest:

dots = dots*1+5; 

the dots will be converted to number.

like image 42
mier Avatar answered Nov 07 '22 15:11

mier