简体   繁体   English

要修剪的JavaScript在字符串中开始为0

[英]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 ? 我有一个时间字符串,格式是HHMM,我需要得到它的小数,我该怎么办?

eg 例如

'1221'=1221 '1221'= 1221

'0101'=101 '0101'= 101

'0011'=11 '0011'= 11

'0001'=1 '0001'= 1

If the string begins with "0x", the radix is 16 (hexadecimal) 如果字符串以“0x”开头,则基数为16(十六进制)

If the string begins with "0", the radix is 8 (octal). 如果字符串以“0”开头,则基数为8(八进制)。

But I want to treat it as decimal no matter whether started with 0 or 00 or 000. 但无论是从0还是00或000开始,我都希望将其视为小数。


additional: 额外:

thanks all. 谢谢大家。

I had know what you said, what make I confused as following : 我知道你说了什么,是什么让我困惑如下:

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

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

so II doubt parseInt() and have this question . 所以我怀疑parseInt()并有这个问题。

Use parseInt() and specify the radix yourself. 使用parseInt()并自己指定基数。

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. 注意:您应该始终提供可选的radix参数,因为如果没有提供,parseInt将尝试自己解决它。 This can lead to some very weird behavior. 这可能会导致一些非常奇怪的行为。


Update: 更新:

This is a bit of a hack. 这有点像黑客。 But try using a String object: 但是尝试使用String对象:

var s = "0300";

parseInt(s, 10); // 300

The down-side of this hack is that you need to specify a string-variable. 这个hack的缺点是你需要指定一个字符串变量。 None of the following examples will work: 以下示例均不起作用:

parseInt(0300 + "", 10);              // 192    
parseInt(0300.toString(), 10);        // 192    
parseInt(Number(0300).toString(), 10) // 192

You can supply the radix parameter to parseInt() : 您可以为parseInt()提供radix参数:

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

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. 如果你想把它变成一个数字,roosteronacid有正确的代码。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM