tags:

views:

118

answers:

5

I hava a time string,the format is HHMM, I need to get the decimal of it, how can I do ?

e.g.

'1221'=1221

'0101'=101

'0011'=11

'0001'=1

If the string begins with "0x", the radix is 16 (hexadecimal)

If the string begins with "0", the radix is 8 (octal).

But I want to treat it as decimal no matter whether started with 0 or 00 or 000.


additional:

thanks all.

I had know what you said, what make I confused as following :

var temp1=0300; var temp2='0300';

parseInt(temp1,10)=192; parseInt(temp1,10)=300;

so I I doubt parseInt() and have this question .

+6  A: 

Use parseInt() and specify the radix yourself.

parseInt("10")     // 10
parseInt("10", 10) // 10
parseInt("010")    //  8
parseInt("10", 8)  //  8
parseInt("0x10")   // 16
parseInt("10", 16) // 16

Note: You should always supply the optional radix parameter, since parseInt will try to figure it out by itself, if it's not provided. This can lead to some very weird behavior.


Update:

This is a bit of a hack. But try using a String object:

var s = "0300";

parseInt(s, 10); // 300

The down-side of this hack is that you need to specify a string-variable. None of the following examples will work:

parseInt(0300 + "", 10);              // 192    
parseInt(0300.toString(), 10);        // 192    
parseInt(Number(0300).toString(), 10) // 192
roosteronacid
I would rather say: You *need* to specify the radix.
Gumbo
@Gumbo - except of course that isn't true ;P You *should* specify the radix.
annakata
roosteronacid
+2  A: 

You can supply the radix parameter to parseInt():

var x = '0123';
x = parseInt(x, 10); // x == 123
Greg
In this case need to be careful with radix parameter, it's results may be unexpected: parseInt('0x300', 16); => 768 parseInt('0x300', 8); => 0
Anatoliy
+1  A: 

If you want to keep it as a string, you can use regex:

num = num.replace(/^0*/, "");

If you want to turn it unto a number roosteronacid has the right code.

Glenn
thanks.I had know what you said, what make I confused as following :var temp1=0300; var temp2='0300';parseInt(temp1,10)=192; parseInt(temp1,10)=300;so I I doubt parseInt() and have this question .
Cong De Peng
A: 
Number("0300") = Number(0300) = 300
Jakob Stoeck
Number(0300) = 192
Anax
A: 

Solution here:

function parse_int(num) {
    var radix = 10;
    if (num.charAt(0) === '0') {
        switch (num.charAt(1)) {
        case 'x':
            radix = 16;
            break;
        case '0':
            radix = 10;
            break;
        default:
            radix = 8;
            break;
    }
    return parseInt(num, radix);
}
var num8 = '0300';
var num16 = '0x300';
var num10 = '300';
parse_int(num8);  // 192
parse_int(num16); // 768
parse_int(num10); // 300
Anatoliy
This won't work with 0030.
Anax
Ops. This is fixed now.
Anatoliy