Cong De Peng
Cong De Peng

Reputation: 321

JavaScript to trim started 0 in a string

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 .

Upvotes: 4

Views: 5232

Answers (5)

Anatoliy
Anatoliy

Reputation: 30073

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

Upvotes: 0

cllpse
cllpse

Reputation: 21727

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

Upvotes: 6

Jakob Stoeck
Jakob Stoeck

Reputation: 624

Number("0300") = Number(0300) = 300

Upvotes: 0

Glenn
Glenn

Reputation: 5342

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.

Upvotes: 4

Greg
Greg

Reputation: 321678

You can supply the radix parameter to parseInt():

var x = '0123';
x = parseInt(x, 10); // x == 123

Upvotes: 2

Related Questions