Is there any way on python to have two integers and merge them in a single float?
for example i have two variable var1=2 and var2=4 and i want to create a new variable var3=2.4
Integers and floating-point numbers can be mixed in arithmetic. Python 3 automatically converts integers to floats as needed.
If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.
Use the syntax print(str(INT)) to return the int as a str , or string.
You can do it through string:
>>> var1=2
>>> var2=4
>>> var3=float(str(var1)+"."+str(var2))
>>> var3
2.3999999999999999
Efficient method that works for any a and b:
from math import floor, log10
def combine(a, b):
if b == 0:
return a
return a + b * 10**-(floor(log10(b))+1)
Testing timing for this method and fredtantini's version:
from timeit import Timer
from random import randint
from math import floor, log10
def random_pair_generator(n):
i = 0
while i < n:
yield (randint(1, 1000000000), randint(1, 1000000000))
i += 1
def maths_combine(a, b):
if b == 0:
return float(a)
return a + b * 10**-(floor(log10(b))+1)
def string_combine(a, b):
return float(str(a) + '.' + str(b))
def time(n):
maths_time, string_time = 0, 0
for a, b in random_pair_generator(n):
maths_time += Timer(lambda: maths_combine(a, b)).timeit()
string_time += Timer(lambda: string_combine(a, b)).timeit()
print('Maths time:', maths_time)
print('String time:', string_time)
>>> time(20)
Maths time: 31.402130099450005
String time: 49.468994391525484
As expected, using maths is much faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With