0

When I tried to explore difference between pareseInt(), parseFloat() and Number() I absorbed this difference.

parseInt("10e+1"); // 10
parseFloat("10e+1"); // 100
Number ("10e+1"); // 100

When I read the document about parseFloat() on Mozilla web docs, I understood that the parseFloat() will accept exponent. Where as there is no specific point about this for parseInt(). I am very much interested to know why this difference in these similar methods

Kalaivanan
  • 459
  • 2
  • 8
  • 17
  • 1
    Your question contains the answer; `parseInt()` is just different from `parseFloat()` and it only pays attention plain digits, returning an integer. – Pointy May 29 '18 at 12:06
  • 1
    Possible duplicate of [parseInt() parses number literals with exponent incorrectly](https://stackoverflow.com/questions/30160919/parseint-parses-number-literals-with-exponent-incorrectly) – Krypt1 May 29 '18 at 12:06
  • 1
    Possible duplicate of [difference between parseInt() and parseFloat()](https://stackoverflow.com/questions/12812863/difference-between-parseint-and-parsefloat) – Gezzasa May 29 '18 at 12:06
  • @Pointy i am not compromised with your answer. Can yoy explain me bit more? – Kalaivanan May 29 '18 at 12:09
  • Have you checked the other questions mentioned in the other answers? `parseInt()` only looks at digits. Any other character, like a "." or "e", causes it to stop parsing and return the integer it's seen so far in the source string. That's just the way it works. – Pointy May 29 '18 at 12:14

2 Answers2

3

parseInt does not understand exponantial notation. However it can parse number in a string which is a number concatenated with characters. Following will also return 10 :

parseInt("10something")
Camille Vienot
  • 727
  • 8
  • 6
1

JavaScript provides two methods for converting non-number primitives into numbers: parseInt() and parseFloat() . As you may have guessed, the former converts a value into an integer whereas the latter converts a value into a floating-point number.

  • "10e+1" is a string, and parseInt() does not recognize exponential notation, so it stops at the second letter.
  • 10e+1 is a number literal that evaluates to 100; parseInt() sees 100 and happily returns that.
  • "10e+1" as a string is perfectly fine when parsed as a float.

Example:

console.log( 'parseInt( 10e+1 ) return: ' + parseInt( 10e+1 ) );
console.log( 'parseInt( "10e+1" ) return: ' + parseInt( '10e+1' ) );
console.log( 'parseFloat( 10e+1 ) return: ' + parseFloat( 10e+1 ) );
console.log( 'parseFloat( "10e+1" ) return: ' + parseFloat( '10e+1' ) );
Kavian K.
  • 1,340
  • 1
  • 9
  • 11