Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: error when using parseInt() on a number

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.

In JavaScript, parseInt(1.2) would yield 1 with no errors, however, in TypeScript, it throws an error during compilation saying:

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

Am I missing something here or is it an expected behaviour from TypeScript?

like image 893
benjaminz Avatar asked Sep 13 '16 16:09

benjaminz


People also ask

What happens if you parseInt a number?

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .

How do you use parseInt in typescript?

Use the parseInt() function to convert a string to a number, e.g. const num1 = parseInt(str) . The parseInt function takes the value to parse as a parameter and returns an integer parsed from the provided string.

Does parseInt have a limit?

Your number is too large to fit in an int which is 32 bits and only has a range of -2,147,483,648 to 2,147,483,647. Try Long. parseLong instead.

Does parseInt round the number?

parseInt() easily converts your string to a rounded integer. In these cases, simply define your string argument and set the radix to 10 (or if you have a special use-case, another numerical value).


1 Answers

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.

like image 64
Ryan Cavanaugh Avatar answered Sep 19 '22 15:09

Ryan Cavanaugh