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?

1
  • 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 Commented Sep 14, 2012 at 9:58

5 Answers 5

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));​
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

In ES5 that behaviour is removed, but it persists in browsers, perhaps for backwards compatibility. I wonder how much code actually depends on it.
0

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

Comments

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

Comments

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]
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.