Turn string into number

Asked

Viewed 1,749 times

2

I have a problem that for many are simple, I have a code that takes the value of a input of the kind hidden and when I pick up this amount, I add +1, ie if the value is 3 it add +1 and have to stay 4:

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

He would have to stay 4 and alter the value from the input to 4:

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

only he returns to me Current Value + 1 that is to say, 31, 41 as if it were string.

2 answers

4

Although you are using jQuery to pick up the attribute, this is standard behavior of the Javascript language. When using the sum operator between a number and a string, the number is converted to string.

My favorite way to solve it is to use the unary operator + in front of the string, like this:

var total = +$("#total").attr('value') + 1;
  • That seems like a trick to me, like using "" + 1 to convert int to string.

  • 1

    It’s different, it’s another operator. It’s not sum, it’s the + unary that serves precisely to force the conversion (see the link in the reply).

  • Cool, I didn’t know you could do it like that. + 1

  • @Andréribeiro +1 or +"1"? ;)

  • @bfavaretto Boa :D

3


You can use the function parseInt to turn the string into 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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.