3

I found this unexpected behavior when trying to break my code... can someone explain to me why this is and what should be the way to make sure the supplied value is a genuine float?

for example:

alert(parseFloat('4.2.2'));

I was expecting NaN... not what I got.

I made a very simple jsfiddle demonstration here.

Jeremy Holovacs
  • 22,480
  • 33
  • 117
  • 254

4 Answers4

7

That is how the parseFloat and parseInt methods work. They parse up to the point where the input becomes invalid. They return NaN only if the first character is invalid..


Quoting the https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseFloat

parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.

If the first character cannot be converted to a number, parseFloat returns NaN.


To check if a string is a number you can use (from Validate decimal numbers in JavaScript - IsNumeric())

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
Community
  • 1
  • 1
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
2

Parse back float to string and compare if they are equal

jonasnas
  • 3,540
  • 1
  • 23
  • 32
2

parseFloat parses its string argument from left-to-right, until it encounters an error condition, at which point it stops parsing.

According to mozilla

parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, parseFloat returns NaN.

So it starts to parse a float from left to right, until it cannot parse it any more. In your case, things work fine until it encounters the second decimal place. At that point, it is no longer a valid float, so it stops parsing.

In another example, if you call parseFloat('100ASDF'), it will return 100, and not NaN.

Joe Alfano
  • 10,149
  • 6
  • 29
  • 40
2

Seems basic enough when you read the docs for it:

parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.

j08691
  • 204,283
  • 31
  • 260
  • 272