How do I work around JavaScript's parseInt octal behavior?

后端 未结 10 1629
Happy的楠姐
Happy的楠姐 2020-11-21 07:36

Try executing the following in JavaScript:

parseInt(\'01\'); //equals 1
parseInt(\'02\'); //equals 2
parseInt(\'03\'); //equals 3
parseInt(\'04\'); //equals          


        
相关标签:
10条回答
  • 2020-11-21 07:44
    function parseDecimal(s) { return parseInt(s, 10); }
    

    edit: making your own function, to do what you really want, is just an option if you don't like adding the ",10" all the time to the parseInt() call. It has the disadvantage of being a nonstandard function: more convenient for you if you use it a lot, but perhaps more confusing for others.

    0 讨论(0)
  • 2020-11-21 07:46

    How about this for decimal:

    ('09'-0) === 9  // true
    
    ('009'-0) === 9 // true
    
    0 讨论(0)
  • 2020-11-21 07:48

    You may also, instead of using parseFloat or parseInt, use the unary operator (+).

    +"01"
    // => 1
    
    +"02"
    // => 2
    
    +"03"
    // => 3
    
    +"04"
    // => 4
    
    +"05"
    // => 5
    
    +"06"
    // => 6
    
    +"07"
    // => 7
    
    +"08"
    // => 8
    
    +"09"
    // => 9
    

    and for good measure

    +"09.09"
    // => 9.09
    

    MDN Link

    The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.

    0 讨论(0)
  • 2020-11-21 07:52

    This issue cannot be replicated in latest Chrome nor Firefox (2019).

    0 讨论(0)
  • 2020-11-21 07:53

    This is a common Javascript gotcha with a simple solution:

    Just specify the base, or 'radix', like so:

    parseInt('08',10); // 8
    

    You could also use Number:

    Number('08'); // 8
    
    0 讨论(0)
  • 2020-11-21 07:56

    From the parseInt documentation, use the optional radix argument to specify base-10:

    parseInt('08', 10); //equals 8
    parseInt('09', 10); //equals 9
    

    This strikes me as pedantic, confusing, and verbose (really, an extra argument in every single parseInt?) so I'm hoping there is a Better Way.

    0 讨论(0)
提交回复
热议问题