DCSIMG
JavaScript parseInt method - be careful - Pini Dayan

Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.

JavaScript parseInt method - be careful

Today I solved  a bug in JavaScript for a company I am advising to. The bug had to do to the simple fact that they did not  really understood the ParseInt method. The special thing to notice about this method is the radix (The base ) in which the method works with.

As it turns out, the parseInt method not only gets a string as a parameter and tries to convert it to integer, it can also get a second optional parameter which is the radix. (from 2 to 36). Why is this radix so important? Simple. Because if the string begins with "0" then the function will return "0" no matter what number follows it, this is because the default radix in this case is 8(octal).

So for example:

var sNumber = "8";
alert(parseInt(sNumber));
will alert "8"     
var sNumber2 = "08";
alert(parseInt(sNumber2));will alert "0".

The last line should have been written like this:  alert(parseInt(sNumber2,10));

So next time you are trying to convert a string into int - pay attention.

Comments

אריאל בן חורש said:

Well, true. but this default is stupid....

# May 3, 2009 3:51 PM

Avi Pinto said:

מטורף,

לא הכרתי את הבעיה הזו

תודה

# May 3, 2009 8:12 PM

Shlomo said:

איך עלית על זה ?

# May 3, 2009 11:52 PM

Yoav Michaeli said:

You can use the function Number()

www.w3schools.com/.../jsref_Number.asp

# May 4, 2009 12:14 AM

Pini Dayan said:

עליתי על הבעיה כי אני מעביר קורס שנקרא Advance JavaScript and CSS

אז הכרתי את זה מקרוב

ולגביי Number - זו אכן דרך נוספת להמיר את הטיפוס

אבל זה כבר construcot function

ותקבל מעיין אובייקט בתמורה.

# May 4, 2009 9:39 AM

שלמה גולדברג said:

פיני כתב שצריך להיזהר בעת שימוש ב parseInt היות וברירת המחדל של הפונקציה - היא להשתמש בבסיס 8, ולכן הפעולה

# June 10, 2009 11:44 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: