parseInt("123qwe")

returns 123

Number("123qwe")

returns NaN

In other words parseInt() parses up to the first non-digit and returns whatever it had parsed. Number() wants to convert the entire string into a number, which can also be a float BTW.


EDIT #1: Lucero commented about the radix that can be used along with parseInt(). As far as that is concerned, please see THE DOCTOR's answer below (I'm not going to copy that here, the doc shall have a fair share of the fame...).


EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number() in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat() aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui") also returns NaN). And the biggest difference is the use of radix that Number() doesn't know of and parseInt() may indirectly guess from the given string (that can cause weird results sometimes).

Answer from sjngm on Stack Overflow
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ parseInt
parseInt() - JavaScript | MDN
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_parseint.asp
JavaScript parseInt() Method
The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10.
Discussions

Basic JavaScript - Use the parseInt Function
Your code so far var a =parseInt(); ... AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54 Challenge: Basic JavaScript - Use the parseInt Function Link to the challenge:... More on forum.freecodecamp.org
๐ŸŒ forum.freecodecamp.org
0
December 20, 2022
javascript - Calling parseInt with a string which represents a value larger than Number.MAX_SAFE_INTEGER - Stack Overflow
I would like to ask about the behavior of parseInt when called with a string which represents an integer value larger than Number.MAX_SAFE_INTEGER. Technically, I assume I should be expecting the ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How can I convert a string to an integer in JavaScript? - Stack Overflow
So if you have noticed parseInt ... to retain the values after decimals. Use parseInt if and only if you are sure that you want the integer value. ... The question was "How do I convert a String into an integer in javascript" 2015-09-02T14:08:16.32Z+00:00... More on stackoverflow.com
๐ŸŒ stackoverflow.com
[AskJS] Explaining parseInt in JavaScript with Scientific Notation
Don't pass a float to a function expecting a string that represents an integer and be surprised at the result being garbage. More on reddit.com
๐ŸŒ r/javascript
9
2
January 31, 2024
Top answer
1 of 6
421
parseInt("123qwe")

returns 123

Number("123qwe")

returns NaN

In other words parseInt() parses up to the first non-digit and returns whatever it had parsed. Number() wants to convert the entire string into a number, which can also be a float BTW.


EDIT #1: Lucero commented about the radix that can be used along with parseInt(). As far as that is concerned, please see THE DOCTOR's answer below (I'm not going to copy that here, the doc shall have a fair share of the fame...).


EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number() in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat() aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui") also returns NaN). And the biggest difference is the use of radix that Number() doesn't know of and parseInt() may indirectly guess from the given string (that can cause weird results sometimes).

2 of 6
89

The first one takes two parameters:

parseInt(string, radix)

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with "0x", the
    radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). This feature
    is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

The other function you mentioned takes only one parameter:

Number(object)

The Number() function converts the object argument to a number that represents the object's value.

If the value cannot be converted to a legal number, NaN is returned.

๐ŸŒ
DEV Community
dev.to โ€บ darkmavis1980 โ€บ you-should-stop-using-parseint-nbf
You should stop using `parseInt()` - DEV Community
October 15, 2021 - This means that if you pass a string like 5e2 , it parseInt will stop when it sees the e and it will just return 5, while Number will evaluate the whole string and return the correct value 500.
๐ŸŒ
Priyanku's Blog
priyankuhazarika.hashnode.dev โ€บ weird-javascript-the-strange-behaviour-of-parseint
Weird Javascript: The Strange behaviour of parseInt()
April 21, 2024 - Here Javascript will first parse 0 and will stop while parsing the next character because it is a decimal, and will finally yield the result 0. It's important to note that parseInt() is primarily used to parse strings into integer values, and it may not always behave as expected with decimal numbers.
Find elsewhere
๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ javascript
Basic JavaScript - Use the parseInt Function - JavaScript - The freeCodeCamp Forum
December 20, 2022 - not sure what I have done. Your code so far var a =parseInt(); function convertToInteger(str) { return parseInt(str); } convertToInteger("56"); console.log(parseInt) Your browser information: User Agent is: Moโ€ฆ
Top answer
1 of 1
2

The problem is fundamental with number representations - any numeric that is over Number.MAX_SAFE_INTEGER is not safe for use any more. Basic example:

const max = Number.MAX_SAFE_INTEGER;
const maxPlus1 = Number.MAX_SAFE_INTEGER + 1;
const maxPlus2 = Number.MAX_SAFE_INTEGER + 2;

console.log("max:", max); //9007199254740991
console.log("max + 1:", maxPlus1); //9007199254740992
console.log("max + 2:", maxPlus2); //9007199254740992

console.log("max + 1 = max + 2:", maxPlus1 === maxPlus2); //true

As you can see, almost immediately after you breach the Number.MAX_SAFE_INTEGER barrier, you run into problems with precision. JavaScript uses the IEEE 754 standard to represents numbers and while it can show numbers than its highest (as opposed to, say an int field in another language which will overflow to zero or maximum negative), such representations are imprecise. Some big numbers cannot be represented like 9007199254740993 (which is Number.MAX_SAFE_INTEGER + 2) and you get a different number instead.

The exact same thing applies to parseInt, since it will convert the string into a JavaScript numeric, there might not be a precise representation for it:

const maxPlus1String = "9007199254740992";
const maxPlus2String = "9007199254740993";

const maxPlus1 = parseInt(maxPlus1String);
const maxPlus2 = parseInt(maxPlus2String);

console.log("max + 1:", maxPlus1); //9007199254740992
console.log("max + 2:", maxPlus2); //9007199254740992

console.log("(string) max + 1 = max + 2:", maxPlus1String === maxPlus2String); //false
console.log("max + 1 = max + 2:", maxPlus1 === maxPlus2); //true

Ultimately, it's a question of how floating point numbers are represented. Wikipedia has a good article but I'll simplify it to the most important parts:

With floating point representation, you keep a mantissa (also called significand with d at the end) and exponent for each number. This works like scientific notation, so I'll use that for easier referencing:

1.23e5 = 1.23 * 105 = 123 000

  • 1.23 is the mantissa of the number.
  • 5 is the exponent.

With both of these, you can represent numbers arbitrarily high in very short form. However, with floating point representation, you are limited to how many bits of each you can keep. This comes at the cost of sacrificing accuracy once you run out of numbers for the mantissa, you lose precision. So, if we decide to only allow one decimal place in our scientific notation, we get the number 1.2e5 which could be 123 000 but it might also be 120 000 or 125 000 or 128 215 - we cannot recreate it from the shortened form. Similar thing happens with floating point numbers - once you don't have enough digits for the mantissa, the rest are discarded, so you don't get the exact number back.

When the exponent runs out of digits you reach the highest number representable.

In JavaScript, the maximum number possible can be seen in Number.MAX_VALUE:

console.log(Number.MAX_VALUE)

1.7976931348623157e+308 is pretty large, with an exponent of 308. So you can represent a lot of numbers with this and if you use parseInt anything under this value, you will get some number that is in the region of what you parsed.

However, what happens if you go over? Well, you'll reach a value within the number range that is representable in JavaScript which is reserved for a special reason. This is the absolute top most number - a floating point representation for the largest number possible to be represented. That value is Infinity. If you happen to parse something that is larger than Number.MAX_VALUE, you'll get Infinity instead:

const largeNum = "17" + "0".repeat(307); //1.7e308
const tooLargeNum = "18" + "0".repeat(307); //1.8e308

console.log("large number string:", largeNum);
console.log("large number parsed:", parseInt(largeNum));


console.log("too large number string:", tooLargeNum);
console.log("too large number parsed:", parseInt(tooLargeNum));

So, even if you have astronomically large numbers, you are guaranteed to have a number more than zero, since Infinity > 0

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ javascript-number-parseint-method
JavaScript Number parseInt() Method - GeeksforGeeks
3 weeks ago - The parseInt() method parses a value by converting it to a string and returns the first integer found. It also accepts an optional radix parameter that specifies the base of the numeral system.
๐ŸŒ
KeyCDN
keycdn.com โ€บ support โ€บ parseint
parseInt() - Explained with Examples - KeyCDN Support
March 15, 2020 - parseInt() is a JavaScript function that parses a string and returns an integer.
Top answer
1 of 16
3113

The simplest way would be to use the native Number function:

var x = Number("1000")

If that doesn't work for you, then there are the parseInt, unary plus, parseFloat with floor, and Math.round methods.

parseInt()

var x = parseInt("1000", 10); // You want to use radix 10
    // So you get a decimal number even with a leading 0 and an old browser ([IE8, Firefox 20, Chrome 22 and older][1])

Unary plus

If your string is already in the form of an integer:

var x = +"1000";

floor()

If your string is or might be a float and you want an integer:

var x = Math.floor("1000.01"); // floor() automatically converts string to number

Or, if you're going to be using Math.floor several times:

var floor = Math.floor;
var x = floor("1000.01");

parseFloat()

If you're the type who forgets to put the radix in when you call parseInt, you can use parseFloat and round it however you like. Here I use floor.

var floor = Math.floor;
var x = floor(parseFloat("1000.01"));

round()

Interestingly, Math.round (like Math.floor) will do a string to number conversion, so if you want the number rounded (or if you have an integer in the string), this is a great way, maybe my favorite:

var round = Math.round;
var x = round("1000"); // Equivalent to round("1000", 0)
2 of 16
306

Try parseInt function:

var number = parseInt("10");

But there is a problem. If you try to convert "010" using parseInt function, it detects as octal number, and will return number 8. So, you need to specify a radix (from 2 to 36). In this case base 10.

parseInt(string, radix)

Example:

var result = parseInt("010", 10) == 10; // Returns true

var result = parseInt("010") == 10; // Returns false

Note that parseInt ignores bad data after parsing anything valid.
This guid will parse as 51:

var result = parseInt('51e3daf6-b521-446a-9f5b-a1bb4d8bac36', 10) == 51; // Returns true
๐ŸŒ
Dmitri Pavlutin
dmitripavlutin.com โ€บ parseint-mystery-javascript
Solving a Mystery Behavior of parseInt() in JavaScript
April 20, 2021 - parseInt() is a built-in JavaScript function that parses integers from numerical strings.
๐ŸŒ
Tabnine
tabnine.com โ€บ home โ€บ how to use parseint() in javascript
How to Use parseInt() in JavaScript - Tabnine
July 25, 2024 - Note: The letter โ€œeโ€ is often used to indicate a number stored in scientific notation (for example, 4.38e12 = 4.38 X 10ยนยฒ). With parseInt(), โ€œeโ€ is read only if it is included in the radixโ€™s valid character list, and only as a numeral โ€“ this can be different than what is intended by the original string.
๐ŸŒ
Medium
medium.com โ€บ @emreavcilar โ€บ javascript-parseint-vs-number-8186ef8e29c1
JavaScript: parseInt() vs Number() | by Emre Avcฤฑlar | Medium
September 11, 2023 - JavaScript: parseInt() vs Number() This is an issue that I see in projects. In this article, I will explain why you should use Number() instead of parseInt(). You need a variable that contains a โ€ฆ
๐ŸŒ
Reddit
reddit.com โ€บ r/javascript โ€บ [askjs] explaining parseint in javascript with scientific notation
r/javascript on Reddit: [AskJS] Explaining parseInt in JavaScript with Scientific Notation
January 31, 2024 -

Hey everyone in r/javascript,

I recently came across a tweet questioning how JavaScript's parseInt function behaves with numbers like 0.5, 0.05, 0.005, etc., and why it returns 5 for 0.0000005.

Here's a concise explanation: JavaScript represents numbers smaller than 1e-6 in scientific notation. For example, 0.0000005 becomes '5e-7'. When parseInt is used on this string, it reads up to the first non-numeric character, which in this case is 'e'. Therefore, parseInt('5e-7') results in 5.

This behaviour is a mix of how JavaScript handles number-to-string conversion for small numbers and the workings of parseInt. Thought this might be an interesting share for those puzzled by JavaScript's quirky nature!

here is an image for more explanation

https://twitter.com/ibrahimwithi/status/1751563262418674151/photo/1

๐ŸŒ
DEV Community
dev.to โ€บ ussdlover โ€บ understanding-parseint-in-javascript-4a24
Understanding parseInt() in JavaScript - DEV Community
July 29, 2023 - As a JavaScript developer, you might come across various scenarios where you need to convert a string representation of a number into an actual integer. JavaScript provides a built-in function called parseInt() for this purpose. However, one aspect that can be confusing for some developers is the concept of the radix parameter.
๐ŸŒ
YouTube
youtube.com โ€บ chart js
ParseInt Method JavaScript - YouTube
ParseInt Method JavaScript. The ParseInt Method in JavaScript converts a variable string into a number or more specific an integer. Which means always in com...
Published ย  February 27, 2021
Views ย  9K
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ can someone explain mdn's parseint function example?
r/learnjavascript on Reddit: Can someone explain MDN's parseInt function example?
June 20, 2022 -

function roughScale(x, base) {

const parsed = Number.parseInt(x, base);

if (Number.isNaN(parsed)) { return 0; }

return parsed * 100;

}

console.log(roughScale(' 0xF', 16)); // expected output: 1500

console.log(roughScale('321', 2)); // expected output: 0

I understand that parseInt is a method used to parse a string and return an integer. But I'm kind of confused how the function gets the expected output results.

Wouldn't the returned parsed values be:

(0, 16) * 100?

and

(321,16) * 100?

So why are the expected output 1500 and 0?

Also what does 'Number.NaN(parsed)' mean does it mean if the string parsed is not a number it would return 0?

๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ parseint-in-javascript-js-string-to-int-example
parseInt() in JavaScript โ€“ JS String to Int Example
February 11, 2022 - In this tutorial, we will talk about the parseInt function in JavaScript. This function parses (break down) a string and returns an integer or NaN (Not a Number). How the parseInt function works The main purpose of using the parseInt function ...