Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string represents a float number

Tags:

python

decimal

I'm using this to check if a variable is numeric, I also want to check whether it's a floating point number.

if(width.isnumeric() == 1)
like image 776
Harry Krek Avatar asked Mar 05 '16 00:03

Harry Krek


People also ask

How do you check if a value is a float?

Use the isinstance() function to check if a number is an int or float, e.g. if isinstance(my_num, int): . The isinstance function will return True if the passed in object is an instance of the provided class ( int or float ). Copied!

Can a string be a float?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number.

How do you check if a string is a float Java?

To check if a string is a valid Float, use the Float. parseFloat() method, with the string to be checked passed as a parameter.


1 Answers

The easiest way is to convert the string to a float with float():

>>> float('42.666')
42.666

If it can't be converted to a float, you get a ValueError:

>>> float('Not a float')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'Not a float'

Using a try/except block is typically considered the best way to handle this:

try:
  width = float(width)
except ValueError:
  print('Width is not a number')

Note you can also use is_integer() on a float() to check if it's an integer:

>>> float('42.666').is_integer()
False
>>> float('42').is_integer()
True
like image 105
Martin Tournoij Avatar answered Sep 22 '22 00:09

Martin Tournoij