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

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?

This question is related to javascript string math addition

The answer is


You can add + behind the variable and it will force it to be an integer

var dots = 5
    function increase(){
        dots = +dots + 5;
    }

DON'T FORGET - Use parseFloat(); if your dealing with decimals.


its really simple just

var total = (1 * yourFirstVariablehere) + (1 * yourSecondVariablehere)

this forces javascript to multiply because there is no confusion for * sign in javascript.


the simplest:

dots = dots*1+5;

the dots will be converted to number.


After trying most of the answers here without success for my particular case, I came up with this:

dots = -(-dots - 5);

The + signs are what confuse js, and this eliminates them entirely. Simple to implement, if potentially confusing to understand.


I'm adding this answer because I don't see it here.

One way is to put a '+' character in front of the value

example:

var x = +'11.5' + +'3.5'

x === 15

I have found this to be the simplest way

In this case, the line:

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

could be changed to

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

to force it to a number

NOTE:

+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5

parseInt() should do the trick

var number = "25";
var sum = parseInt(number, 10) + 10;
var pin = number + 10;

Gives you

sum == 35
pin == "2510"

http://www.w3schools.com/jsref/jsref_parseint.asp

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


Number()

dots = document.getElementById("txt").value;
dots = Number(dots) + 5;

// from MDN
Number('123')     // 123
Number('123') === 123 /// true
Number('12.3')    // 12.3
Number('12.00')   // 12
Number('123e-1')  // 12.3
Number('')        // 0
Number(null)      // 0
Number('0x11')    // 17
Number('0b11')    // 3
Number('0o11')    // 9
Number('foo')     // NaN
Number('100a')    // NaN
Number('-Infinity') //-Infinity

UPDATED since this was last downvoted....

I only saw the portion

var dots = 5
function increase(){
    dots = dots+5;
}

before, but it was later shown to me that the txt box feeds the variable dots. Because of this, you will need to be sure to "cleanse" the input, to be sure it only has integers, and not malicious code.

One easy way to do this is to parse the textbox with an onkeyup() event to ensure it has numeric characters:

<input size="40" id="txt" value="Write a character here!" onkeyup="GetChar (event);"/>

where the event would give an error and clear the last character if the value is not a number:

<script type="text/javascript">
    function GetChar (event){
        var keyCode = ('which' in event) ? event.which : event.keyCode;
        var yourChar = String.fromCharCode();
        if (yourChar != "0" &&
            yourChar != "1" &&
            yourChar != "2" &&
            yourChar != "3" && 
            yourChar != "4" &&
            yourChar != "5" &&
            yourChar != "6" && 
            yourChar != "7" &&
            yourChar != "8" && 
            yourChar != "9")
        {
            alert ('The character was not a number');
            var source = event.target || event.srcElement;
            source.value = source.value.substring(0,source.value-2);
        }
    }
</script>

Obviously you could do that with regex, too, but I took the lazy way out.

Since then you would know that only numbers could be in the box, you should be able to just use eval():

dots = eval(dots) + 5;

This also works for you:

dots -= -5;

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to math

How to do perspective fixing? How to pad a string with leading zeros in Python 3 How can I use "e" (Euler's number) and power operation in python 2.7 numpy max vs amax vs maximum Efficiently getting all divisors of a given number Using atan2 to find angle between two vectors How to calculate percentage when old value is ZERO Finding square root without using sqrt function? Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt? How do I get the total number of unique pairs of a set in the database?

Examples related to addition

How to find difference between two columns data? How to force addition instead of concatenation in javascript How to add an integer to each element in a list? How to force JS to do math instead of putting two strings together Time calculation in php (add 10 hours)?