1

Possible Duplicate:
How to parseInt a string with leading 0

I'm using Google Chrome ver. 21.0.1180.89

I execute:

var a="07:30";
console.log(a.substring(0,2)+" --> "+parseInt(a.substring(0,2)));

the output is right: "07 --> 7" OK

I execute:

var a="08:30";
console.log(a.substring(0,2)+" --> "+parseInt(a.substring(0,2)));

the output is right: "08 --> 0" WRONG

why?

Community
  • 1
  • 1
Tommaso Taruffi
  • 8,932
  • 9
  • 44
  • 56
  • the leading 0 denotes OCTAL: 00,01,02,03,04,05,06,07,10 so 08 and 09 are invalid. Add a radix as mentioned – mplungjan Sep 14 '12 at 09:58

5 Answers5

2

String begins with "0" taken as octal. You have to set radix 10 in parseInt()

Try this,

var a="08:30";
console.log(a.substring(0,2)+" --> "+parseInt(a.substring(0,2), 10));​
Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70
0

add a radix(base): parseInt(a.substring(0,2), 10). What's happening is your js engine is trying to guess what base the string is, and it's guessing wrongly, so you need to tell the engine what base to use (2 for binary, 8 for octal10 for decimal, 16 for hex, etc)

SReject
  • 3,774
  • 1
  • 25
  • 41
  • In [ES5](http://ecma-international.org/ecma-262/5.1/#sec-15.1.2.2) that behaviour is removed, but it persists in browsers, perhaps for backwards compatibility. I wonder how much code actually depends on it. – RobG Sep 14 '12 at 10:35
0

You have to use parseInt(a.substring(0,2),10);

Vincent Thibault
  • 601
  • 5
  • 16
0

parseInt take 2 parameters, the string to parse and the radix which is optionnal (but required with JSHint/JSLint). If you don't pass the {radix{ parameter, parseInt will "choose" the best for the string you passed, so for the 08 string, it will take the octal radix and not the decimal one (the one you want).

TL;DR Always set the radix when using parseInt.

source: MDN

Calvein
  • 2,111
  • 13
  • 28
0

If you're dealing with time just to offer a different solution you could try doing it like this:

var clock = '07:30';
var time = {
  hours: +clock.split(':')[0],
  minutes: +clock.split(':')[1]
}
elclanrs
  • 92,861
  • 21
  • 134
  • 171