-2

I have an input where the user introduces a number, integer or float. I would like to know it the number is correct, for example, check that the input 2r is not correct. My first approach was to use parseFloat, but it does not complain about that:

parseFloat('2r')   // returns 2

Actually, this is the expected behaviour according to the docs

How do you check that 2r is wrong?

Andrés
  • 719
  • 1
  • 4
  • 21

3 Answers3

6

This is not an error with parseFloat, seems like you are after something else.

Try Number;

Number('2r'); // returns Nan
C.OG
  • 6,236
  • 3
  • 20
  • 38
2

It ls well documented

If parseFloat encounters a character other than a plus sign (+), minus sign (- U+002D HYPHEN-MINUS), numeral (0–9), decimal point (.), or exponent (e or E), it returns the value up to that character, ignoring the invalid character and characters following it.

The following examples all return 3.14:

parseFloat(3.14);
parseFloat('3.14');
parseFloat('  3.14  ');
parseFloat('314e-2');
parseFloat('0.0314E+2');
parseFloat('3.14some non-digit characters');
parseFloat({ toString: function() { return "3.14" } });
FreeBird72
  • 123
  • 1
  • 2
0

That is expected behaviour - parseFloat and similar will ignore any 'junk' following a real number.

If you need to verify that this is a real number as a whole, then there are various strategies to use, the easiest of which is to try a mathematical operation, such as multiplying by one.

MikeB
  • 580
  • 3
  • 18