TypeScript: error when using parseInt () for a number

The JavaScript parseInt function can be used to force a given parameter to be an integer, regardless of whether the parameter is a string, a floating-point number, a number, etc.

In JavaScript, parseInt(1.2) gives 1 without errors, however in TypeScript it throws an error at compile time, saying:

 error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. 

Am I missing something or is this the expected behavior from TypeScript?

+7
javascript typescript
source share
6 answers

Do not use parseInt to perform this operation - use Math.floor .

Using parseInt to floor , a number will not always give the correct results. parseInt(4e21) returns 4 , not 4e21 . parseInt(-0) returns 0 , not -0 .

+11
source share

The parseInt function really expects a string in its first argument. Please check the documentation . You can usually omit the second radix argument, and then it will revert to the default value of 10 . But the safest thing is always to add a numerical system base as the second argument (usually 10 ).

If you want to assign a common value to number , you can use the number function like this.

 var myNumber = Number(myGeneralValue); 
+4
source share

Look at the input:

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

The first argument must be a string. This is in accordance with the specification:

parseInt (string , radix)
The parseInt function creates an integer value determined by the interpretation of the contents of the string argument in accordance with the specified base.

In regular JS, the first argument is coerced into a string based on the following rule in the specification:

  • Let inputString be ToString (string).

therefore parseInt(1.2) works.

Please note that the specification allows radix to be undefined , which coincides with the absence of it, so the question mark in the radix?: number signature. In this case, of course, by default it is 10 (if the line does not look like 0xabc ).

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

+2
source share

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

+2
source share

There are various manifestations when negative numbers are between "Math.floor" and "parseInt".

you should use this: 1.2 | 0

or (1.2). toFixed (0)

+1
source share

I think other people have already given a lot of valid answers here, but in my opinion, the simplest approach would be to call .toString() original value and use radix explicitly:

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

0
source share

All Articles