Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: parseInt method

1. ## parseInt method

Im working on learning JavaScript with the help of a text book, below is the current script I am working on regarding handling forms. This script should populate the "Days" field depending on the Month selected. I understand most of it except for the parseInt function. Could anyone help describe it to me? I understand it turns a String into a Value...hmm

Code:
```

function initForm() {
document.getElementById("months").selectedIndex = 0;
document.getElementById("months").onchange = populateDays;
}

function populateDays() {
var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var monthStr = this.options[this.selectedIndex].value;

if (monthStr != "") {
var theMonth = parseInt(monthStr);

document.getElementById("days").options.length = 0;
for(var i=0; i<monthDays[theMonth]; i++) {
document.getElementById("days").options[i] = new Option(i+1);
}
}
}```

Thank you! I am very interested in learning this and would love any help!

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

Quizmaster: In maths, what number is represented by 10 to the power of 3?
Contestant: Six.

• Yes, Google and I are friends. We get along quite well actually. I suppose I was just looking for a different explanation. But thanks for the comment.

• I understand it turns a String into a Value...hmm
Well, yeah. Except a String *is* a Value.

It turns a string into an INTEGER value, if possible. Integers are whole numbers (-7, 55, 0, -113, 332, etc.). If the function can't convert the string to an integer, then the result is a special value called NaN ("Not a Number").

Compare parseInt() to parseFloat() andNumber( ).

• basically, when something returned a number as a string, eg:

Code:
```function something() { return "100"; }
var get = something();```
You may not always want to use it as a string, if you need to do math:

Code:
```var num = get + 1;
// at this point num wouldn't be 101... because you cant add a string to an integer and expect a mathematically correct result```
However... the following solves the problem:

Code:
`var num = parseInt(get) + 1;`
Simple.

This can sometimes be common for parsing out a number out of a number+string combination with pixel values:

Code:
```var width = "100px";
var new_width = parseInt(width) + 20;
var final = new_width + 'px';```
The above will take 100px, remove "px" by parseInt, then add 20 to it, then re-ad "px"

This way you can do math on some default values stored in elements which do by default contain the dreaded PX.

• ## Users who have thanked html-tutorials for this post:

Finch (12-17-2011)

• parseInt is for converting numbers between different bases. The original number can be in anything between base 2 (binary) and base 36. The result will always be base 10 (decimal). You can either specify the base the original number is in as the second parameter you supply to parseInt eg. parseInt('afbc91', 16) or have it assume what base you are translating from by the first character of the string - '0x' means base 16 and '0' means base 8.

To convert a string to a number use either:

var num = Number(str);

or

var num = +str;

• In the particular script above (I think this is where I am having trouble understanding the parseInt method), what is the parseint method doing? I will paste the HTML doc that goes along w. this below:

Code:
```<!DOCTYPE html>
<html>
<script src="script02.js"></script>
<body>
<form action="#">
<select id="months">
<option value="">Month</option>
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
&nbsp;

<select id="days">
<option>Day</option>
</select>
</form>

</body>
</html>```
Thanks for all the help everyone, I am starting to understand it more - In this case, is the parseint is turning the var monthStr into a "number"? What does that actually do?

• Originally Posted by Finch
Im working on learning JavaScript with the help of a text book
I'd ditch that text book, if I were you.

Trying to recreate date logic is pretty much always wrong, and should never be advocated in any learning material. There's already a built-in Date object, and not using it not only makes your code harder to maintain, it will most probably also result in a bunch of generalizations that just don't work in the real world:

February doesn't always have 28 days. Sometimes it has 29, and if you want to account for that fact in the piece of code you posted, you'll make the problem worse by introducing additional logic that the Date object already provides in the first place.

Since the Date constructor allows for overflowing values, the logic for determining the number of days in a certain month can be as simple as this:

PHP Code:
``` function monthLength (year, month) {    return new Date(year, month + 1, 0).getDate();}alert(monthLength(2011, 1)); // 28alert(monthLength(2012, 1)); // 29  ```
Code that tries to mimic built-in date logic wastes a ridiculous amount of maintenance cost every year; I'm not nitpicking here — this is a real problem, and any text book that propagates this sort of DIY date logic without any regard to the big picture should be considered harmful.

And to answer your actual question: parseInt converts its argument to a string, discards everything that doesn't make sense for an integer, and returns a new primitive of type `number`. See here for how exactly that works: https://developer.mozilla.org/en/Jav...jects/parseInt

That said, it's pretty much useless in your piece of code, since property names are strings anyway, so you're actually doing a double conversion:

PHP Code:
``` for (var i in [0]) {alert(typeof i);} // string  ```

• Originally Posted by felgall
To convert a string to a number use either:

var num = Number(str);

or

var num = +str;
Or var num = num*1;

The value returned from a select list value is a string value. But as I see it the values are not used in any case. The code is using selectedIndex which is already a number, so the parseInt() has no purpose in this case. Perhaps that is why you are having trouble understanding it.

Take a little time to study this code:-

Code:
```	<select id="months" onchange = "showValue()">
<option value="">Month</option>
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
</select>

<script type = "text/javascript">

function showValue() {
var myArray = ["Jan", "Feb", "Mar", "Apr"];
var val = document.getElementById("months").value;
alert (val + "  " + typeof val);
alert (myArray[val]);  // although val is a string value Javascript will interpret it as a number here
var si = document.getElementById("months").selectedIndex;
alert (si + "   " + typeof si);
var txt = document.getElementById("months").options[si].text;
alert (txt);  // the text value of the option
}```
As venegal says, that textbook seems less than instructive.

• Originally Posted by Philip M
The value returned from a select list value is a string value. But as I see it the values are not used in any case. The code is using selectedIndex which is already a number, so the parseInt() has no purpose in this case. Perhaps that is why you are having trouble understanding it.
This doesn't sound right. The value of the selected option is used — namely as an array key — whereas the selectedIndex property is only used to get that value (unnecessarily so, as pointed out in your snippet, since the value of the select itself can be used instead of the value of the selected option).

Also, this is a bit misleading:

Originally Posted by Philip M
Code:
`alert (myArray[val]);  // although val is a string value Javascript will interpret it as a number here`
Internally, all property names (even numerical ones, i.e. array keys) are strings, so there's actually no type coercion going on here.

So, you're right that parseInt serves no purpose in the OP's code, but for the wrong reason: It's not that the thing is already a number — it's a string, and the reason parseInt is useless here is that a string is perfectly fine for accessing elements of an array.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•