Turn string into number

2

I have a problem that for many is simple, I have a code that takes the value of a input of type hidden and when I get this value, I add +1, that is, if the value is 3 it add +1 and has to stay 4:

var total = $("#total").attr('value') + 1;

It would have to stay 4 and change the value of the input to 4:

$("#total").val(total);

asked by anonymous 06.03.2015 / 19:35

2 answers

3

You can use parseInt to transform the string in an integer or parseFloat , if the value is a number with decimal places.

parseInt :

var total = parseInt($("#total").attr('value')) + 1;

parseFloat :

var total = parseFloat($("#total").attr('value')) + 1;
    
06.03.2015 / 19:40
4

Although you are using jQuery to get the attribute, this is default behavior of the JavaScript language. When using the sum operator between a number and a string, the number is converted to string.

My preferred way to resolve this is to use the unary operator + in front of the string, like this:

var total = +$("#total").attr('value') + 1;
    
06.03.2015 / 19:43