116

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?

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Sean
  • 8,401
  • 15
  • 40
  • 48
  • possible duplicate of [Javascript adding two numbers incorrectly](http://stackoverflow.com/questions/3638074/javascript-adding-two-numbers-incorrectly); see [my answer to that question](http://stackoverflow.com/questions/3638074/javascript-adding-two-numbers-incorrectly/4600744#4600744) – Phrogz Jan 30 '11 at 05:44

11 Answers11

119

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.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Alex
  • 3,245
  • 2
  • 19
  • 17
  • 4
    shortcut... dots = +document.getElementById("txt").value – Tracker1 Jan 30 '11 at 08:45
  • 5
    parseInt(..., 10) also, always use a radix... a sanity check... if (!dots || dots < 1) may be in order too... – Tracker1 Jan 30 '11 at 08:47
  • 1
    Better use increment operator for Addition. like VARIABLE++ instead of VAR= VAR+1; – gnganapath Dec 02 '14 at 06:43
  • function add() { var a = prompt('Enter 1st number'); var b = prompt('enter 2nd number'); var c = a + b; console.log('reuslt is ' + c); } add(); for example var a = 5; and var b = 9; then it prints 59 instead of 14; am unable to understand what's going wrong here. – Monu Rohilla Mar 28 '21 at 06:21
  • 1
    @AnkurRohilla `a` and `b` are strings you need them to be numbers so you can do math on them. This is done by `var c = parseInt(a,10)+parseInt(b,10)` – Alex Mar 29 '21 at 12:19
66

the simplest:

dots = dots*1+5;

the dots will be converted to number.

Liam
  • 27,717
  • 28
  • 128
  • 190
mier
  • 704
  • 4
  • 3
22

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

Baby Groot
  • 4,637
  • 39
  • 52
  • 71
Nicolas
  • 341
  • 3
  • 5
18

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
8

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.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Alan L.
  • 370
  • 3
  • 6
5

This also works for you:

dots -= -5;
Holger.Buick
  • 51
  • 1
  • 2
4

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

var dots = 5
    function increase(){
        dots = +dots + 5;
    }
HSLM
  • 1,692
  • 10
  • 25
3

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
nkitku
  • 4,779
  • 1
  • 31
  • 27
1

its really simple just

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

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

1

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.

Jay Reeve
  • 11
  • 1
-3

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;
vapcguy
  • 7,097
  • 1
  • 56
  • 52
  • 2
    `eval()` is dangerous if `dots` is from user input, particularly if it's from stored input. [More information](http://stackoverflow.com/a/13167699/118697) – Chad Levy Jun 13 '16 at 20:15
  • @ChadLevy Thanks for the link - a good read - and bringing this up, but in this case the concern was unwarranted, since it wasn't from user input. `dots` was a defined variable that was being incremented and just being mistaken for a string. So I'll qualify my answer that it shouldn't be used lightly, as you said, from user/stored input that could have the potential for evil scripting injection. But also in this case, such injection would cause a math error/exception, anyway, so it really wouldn't do anything, either way. – vapcguy Jun 14 '16 at 14:06
  • For those downvoting because you think `eval()` is so dangerous, you need to look at the code in the context the OP was using. It is not, in this case, because he's using input that is not coming from a textbox or any other form of user input where there could be any form of injection of a non-numeric value! I wish I could downvote your downvotes! – vapcguy Sep 12 '16 at 15:12
  • Another downvoter. Care to explain yourself, instead of just being a sheep? There are times when `eval()` is just fine, and you need to look at the context in which it is being used, instead of just blindly believing everything you read without actually understanding it! – vapcguy Oct 11 '16 at 16:22
  • And for anyone's information, I upvoted Chad's comment only because he's right **IF** it fit his scenario. In the case of the OP's scenario, it doesn't. Sorry that I expect my fellow programmers to be smart enough to know the difference. – vapcguy Oct 11 '16 at 16:23
  • Not the downvoter, but looking at the OP's code it looks like there is an instance where `dots` is assigned from user input: `dots = document.getElementById("txt").value;` (`btnClick()`). I think that highlights the danger of using `eval`, even when you think you're safe by not accepting user input. It's possible that, at some point, the code may be changed to accept user input, thereby opening up a hole. – Chad Levy Oct 11 '16 at 17:20
  • 1
    @ChadLevy Ok, on that count, you are right. I did not look at that section - I was focused on what he put at the top of the page: the code `var dots = 5 function increase(){ dots = dots+5; }` does not use a text field, and assigns using direct variables, not from user input. So that's what I went off of. But I saw you're right that he's assigning that text field `txt` to `dots`, and `dots` is a global variable, and so gets updated by that input. You're right. Thanks. – vapcguy Oct 11 '16 at 18:42