43

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?

4
  • 8
    yep that's the type checker for ya! Commented Sep 13, 2016 at 16:48
  • 1
    try parseInt(""+1.2+"") Commented Sep 13, 2016 at 16:49
  • parseInt([2, 3]) returns 2 but that doesn't mean you should do it... Commented Sep 13, 2016 at 17:14
  • You can parseInt(`${data.adjustProgress}`, 10) so i assumes it is always a string. I find it a bit ridiculous, but hey....we just make due. Commented Sep 3, 2024 at 2:14

8 Answers 8

52

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't think it's the correct way. This will produce a float number with no fractional part. But it is not an integer actually. For example you will expect a float number if you divide it by an integer.
The question asks for string | number Math.floor() only takes number so that doesn't work either. One of the other answers suggests Number() which works but perhaps leaves you with a number with decimal places. Math.floor(Number(stringOrNumber)) seems like a sensible option, but also parseInt("" + row.c, 10) seems somewhat acceptable.
@Cosmo Your statement is incorrect since JavaScript does not have an integer type. JavaScript only has the type "number", which is an IEEE 754 double precision floating-point number.
19

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);

1 Comment

" If this argument is not a string, then it is converted to one using the ToString abstract operation. " Documentation doesn't really describe a required type it should have. the input argument is simply just called "string" for historical reasons.
10

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);

6 Comments

template literals (template strings) parseInt(${X}, 10) is another option as well.
@Mahmoud I think the formatter cut the backticks around your template literal. I don't know how to render your syntax in a comment though...
parseInt(`${X}`, 10) you backslash them as such: this is a \` backtick
@JohannesB how did you do it?
Like I said If you add a \ backslash before a tick \`, it keeps the tick inside code formatting
|
5

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.

Comments

5

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

Math.trunc();

see here for details.

1 Comment

This should be the correct answer as its output is the closest to parseInt
4

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

Comments

1

There are different manifestations when negative numbers between 'Math.floor' and 'parseInt'.

you should use this: 1.2 | 0

or (1.2).toFixed(0)

Comments

0
Math.floor(Number(val)) // Accepts String or Number, rounded down integer 
//OR
Math.round(Number(val)) // Accepts String or Number, give nearest Integer

1 Comment

Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.