Python Forum

Full Version: is it float or is it int?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a big number in a string (maybe type unicode in Python2) to convert to either float or int. i want it to be float if float can represent it and if float isn't the best (if int or long can represent it exactly) then i want it to be int (probably long in Python2). it may be in a form supported by int() with a 2nd argument of 0 such as '0x3' (won't work in float(). it may be in an exponential form like '3e0' (won't work in int()). my thinking is that at least one of these is done under try/except. any suggestions on how to do this?

i am wanting to do this in a function that is given the string (maybe type unicode in Python2) which returns the value or None if neither float nor int/long can represent it.

code simplicity is preferred. not importing a module is preferred but if a module is imported it must be integral to Python and available back as far as Python 2.6 and Python 3.0.
What have you tried?
i have tried nothing, yet. i'm still trying to figure it out. what if you convert a string two different ways and get two numbers that are different? which is correct?