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
How to Update a Python Package
How to Listen For 'Usb Device Inserted' Events in Linux, in Python
How Would I Build Python Myself from Source Code on Ubuntu
How to Get Output from Subprocess.Popen(). Proc.Stdout.Readline() Blocks, No Data Prints Out
Python - Is Time.Sleep(N) Cpu Intensive
How to Make a Python, Command-Line Program Autocomplete Arbitrary Things Not Interpreter
How to Update-Alternatives to Python 3 Without Breaking Apt
Understanding Python Subprocess.Check_Output'S First Argument and Shell=True
How to Store the Result of an Executed Shell Command in a Variable in Python
How to Upgrade Python Version to 3.7
Pythonpath Not Working For Sudo on Gnu/Linux (Works For Root)
Change Default Python Version from 2.4 to 2.6
System-Wide Mutex in Python on Linux
Cross-Platform Space Remaining on Volume Using Python
Force Python to Use an Older Version of Module (Than What I Have Installed Now)
How to Terminate a Python Subprocess Launched With Shell=True
How to Remove Script Tags With Beautifulsoup
Deploying a Minimal Flask App in Docker - Server Connection Issues