Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with javascript "parseInt()" [duplicate]

Tags:

javascript

Possible Duplicate:
Workarounds for JavaScript parseInt octal bug
How to parseInt a string with leading 0

document.write(parseInt("07"));

Produces "7"

document.write(parseInt("08"));

Produces "0"

This is producing problems for me (sorry for this babble, I have to or I can't submit the question). Anyone know why it's being stupid or if there is a better function?

like image 472
joedborg Avatar asked Sep 06 '11 10:09

joedborg


People also ask

What can I use instead of parseInt?

parseFloat( ) parseFloat() is quite similar to parseInt() , with two main differences. First, unlike parseInt() , parseFloat() does not take a radix as an argument. This means that string must represent a floating-point number in decimal form (radix 10), not octal (radix 8) or hexadecimal (radix 6).

Does parseInt have a limit?

Your number is too large to fit in an int which is 32 bits and only has a range of -2,147,483,648 to 2,147,483,647. Try Long. parseLong instead.

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 .

What does parseInt return if not a number?

If s does not begin with a number that parseInt( ) can parse, the function returns the not-a-number value NaN . Use the isNaN( ) function to test for this return value. The radix argument specifies the base of the number to be parsed. Specifying 10 makes parseInt( ) parse a decimal number.


2 Answers

If you argument begins with 0, it will be parsed as octal, and 08 is not a valid octal number. Provide a second argument 10 which specifies the radix - a base 10 number.

document.write(parseInt("08", 10));
like image 191
Dennis Avatar answered Oct 18 '22 22:10

Dennis


use this modification

parseInt("08",10);

rules for parseInt(string, radix)

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with "0x", the radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). This feature is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)
like image 29
Marek Sebera Avatar answered Oct 18 '22 21:10

Marek Sebera