How to Check If a String Is a Number (Float)

How do I check if a string is a number (float)?

Which, not only is ugly and slow

I'd dispute both.

A regex or other string parsing method would be uglier and slower.

I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.

The issue is that any numeric conversion function has two kinds of results

  • A number, if the number is valid
  • A status code (e.g., via errno) or exception to show that no valid number could be parsed.

C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.

I think your code for doing this is perfect.

Checking if a string can be converted to float in Python

I would just use..

try:
float(element)
except ValueError:
print "Not a float"

..it's simple, and it works. Note that it will still throw OverflowError if element is e.g. 1<<1024.

Another option would be a regular expression:

import re
if re.match(r'^-?\d+(?:\.\d+)$', element) is None:
print "Not float"

How do I check that a number is float or integer?

check for a remainder when dividing by 1:

function isInt(n) {
return n % 1 === 0;
}

If you don't know that the argument is a number you need two tests:

function isInt(n){
return Number(n) === n && n % 1 === 0;
}

function isFloat(n){
return Number(n) === n && n % 1 !== 0;
}

Update 2019
5 years after this answer was written, a solution was standardized in ECMA Script 2015. That solution is covered in this answer.

How can I check if a string is a float?

Like this:

if (!isNaN(value) && value.toString().indexOf('.') != -1)
{
alert('this is a numeric value and I\'m sure it is a float.');
}​

Is there a way to check if a string can be a float in C?

The first answer should work if you combine it with %n, which is the number of characters read:

int len;
float ignore;
char *str = "5.23.fkdj";
int ret = sscanf(str, "%f %n", &ignore, &len);
printf("%d", ret==1 && !str[len]);

!str[len] expression will be false if the string contains characters not included in the float. Also note space after %f to address trailing spaces.

Demo

Checking to see if a string is an integer or float

If the string is convertable to integer, it should be digits only. It should be noted that this approach, as @cwallenpoole said, does NOT work with negative inputs beacuse of the '-' character. You could do:

if NumberString.isdigit():
Number = int(NumberString)
else:
Number = float(NumberString)

If you already have Number confirmed as a float, you can always use is_integer (works with negatives):

if Number.is_integer():
Number = int(Number)


Related Topics



Leave a reply



Submit