Handles hex, octal, binary, decimal, and float
This solution will handle all of the string conventions for numbers (all that I know about).
def to_number(n):
''' Convert any number representation to a number
This covers: float, decimal, hex, and octal numbers.
'''
try:
return int(str(n), 0)
except:
try:
return int('0o' + n, 0)
except:
return float(n)
This test case output illustrates what I'm talking about.
======================== CAPTURED OUTPUT =========================
to_number(3735928559) = 3735928559 == 3735928559
to_number("0xFEEDFACE") = 4277009102 == 4277009102
to_number("0x0") = 0 == 0
to_number(100) = 100 == 100
to_number("42") = 42 == 42
to_number(8) = 8 == 8
to_number("0o20") = 16 == 16
to_number("020") = 16 == 16
to_number(3.14) = 3.14 == 3.14
to_number("2.72") = 2.72 == 2.72
to_number("1e3") = 1000.0 == 1000
to_number(0.001) = 0.001 == 0.001
to_number("0xA") = 10 == 10
to_number("012") = 10 == 10
to_number("0o12") = 10 == 10
to_number("0b01010") = 10 == 10
to_number("10") = 10 == 10
to_number("10.0") = 10.0 == 10
to_number("1e1") = 10.0 == 10
Here is the test:
class test_to_number(unittest.TestCase):
def test_hex(self):
values = [
(0xDEADBEEF , 3735928559),
("0xFEEDFACE", 4277009102),
("0x0" , 0),
(100 , 100),
("42" , 42),
]
values += [
(0o10 , 8),
("0o20" , 16),
("020" , 16),
]
values += [
(3.14 , 3.14),
("2.72" , 2.72),
("1e3" , 1000),
(1e-3 , 0.001),
]
values += [
("0xA" , 10),
("012" , 10),
("0o12" , 10),
("0b01010" , 10),
("10" , 10),
("10.0" , 10),
("1e1" , 10),
]
for _input, expected in values:
value = to_number(_input)
if isinstance(_input, str):
cmd = 'to_number("{}")'.format(_input)
else:
cmd = 'to_number({})'.format(_input)
print("{:23} = {:10} == {:10}".format(cmd, value, expected))
self.assertEqual(value, expected)
type(my_object)
on it. The result can usually be called as a function to do the conversion. For instancetype(100)
results inint
, so you can callint(my_object)
to try convertmy_object
to an integer. This doesn't always work, but is a good "first guess" when coding. – robertlaytonint(x) if int(x) == float(x) else float(x)
– tcpaivaValueError: invalid literal for int() with base 10: '1.5'
. – marcelm