TypeScript: error when using parseInt() on a number

前端 未结 7 1011
心在旅途
心在旅途 2021-02-18 15:47

The JavaScript function parseInt can be used to force conversion of a given parameter to an integer, whether that parameter is a string, float number, number, etc.

相关标签:
7条回答
  • 2021-02-18 15:53

    Look at the typing:

      parseInt(string: string, radix?: number): number;
                       ^^^^^^
    

    The first argument needs to be a string. That's in line with the spec:

    parseInt (string , radix)
    The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix.

    In normal JS, the first argument is coerced to a string, based on the following rule in the spec:

    1. Let inputString be ToString(string).

    which is why parseInt(1.2) works.

    Note that the spec allows radix to be undefined, which is the same as omitting it, hence the question mark in the radix?: number part of the signature. In this case, of course, it defaults to 10 (unless the string looks like 0xabc).

    As mentioned in other answers, parseInt is not the best solution anyway if what you really want to do is a floor or truncation operation.

    0 讨论(0)
  • 2021-02-18 15:53

    Why would you use parseInt in this case? Just use Math.floor or Math.ceil. parseInt expects a string as an argument and not a number. Hence your error

    0 讨论(0)
  • 2021-02-18 15:59

    A bit old but to put another way in to the pot:

    Math.trunc();

    see here for details.

    0 讨论(0)
  • 2021-02-18 16:01

    Don't use parseInt to do this operation -- use Math.floor.

    Using parseInt to floor a number is not always going to yield correct results. parseInt(4e21) returns 4, not 4e21. parseInt(-0) returns 0, not -0.

    0 讨论(0)
  • 2021-02-18 16:02

    The function parseInt indeed expects a string in its first argument. Please check the documentation. Usually you can omit the second, radix argument and then it will fall back to the default of 10. But the safest is to always add the numeric system base as second argument (usually 10).

    If you'd like to cast a general value to number, you can use the Number function, like this.

    var myNumber = Number(myGeneralValue);
    
    0 讨论(0)
  • 2021-02-18 16:03

    I think other people have already given lots of valid answers here, but in my opinion the easiest approach would be to call .toString() on the original value, and to explicit the radix:

    parseInt((1.2).toString(), 10);

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