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.
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)
TheparseInt
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:
- 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.