Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript String to int conversion

I have the following JS immbedded in a page:

var round = Math.round; var id = $(this).attr("id");  var len = id.length; var indexPos = len -1; // index of the number so that we can split this up and used it as a title  var pasType = id.substring(0, indexPos); // adult, child or infant var ind = round(id.substring(indexPos)); // converts the string index to an integer var number = (id.substring(indexPos) + 1); // creates the number that will go in the title window.alert(number); 

id will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.

The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01, not 1. When testing this with adult1 the alert I get is 11.

I'm using this question for reference, and have also tried var number += id.substring(indexPos);, which breaks the JS (unexpected identifier '+=')

Does anyone know what I'm doing wrong? Is there a better way of doing this?

like image 203
Skytiger Avatar asked Sep 10 '13 07:09

Skytiger


People also ask

What happens if you parseInt a string JavaScript?

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .


1 Answers

The parseInt() function parses a string and returns an integer,10 is the Radix or Base [DOC]

var number = parseInt(id.substring(indexPos) , 10 ) + 1; 
like image 85
Charaf JRA Avatar answered Sep 23 '22 04:09

Charaf JRA