0

What's the fastest way to concentrate two int into one decimal.

eg.

a=100
b=10

to get = 100.10

Thanks.

4 Answers4

2

Convert them into strings and then add them and again convert them

c = float(str(a) + '.'  + str(b))

Output:

100.10
SAI SANTOSH CHIRAG
  • 2,046
  • 1
  • 10
  • 26
1

Assuming python >= 3.6:

a = 100
b = 10

# if you want a string
c = f'{a}.{b}' 

# if you want a float
d = float(f'{a}.{b}')  

It should be a little bit faster than string concatenation, see here.

asikorski
  • 882
  • 6
  • 20
0

Play with string concatenation

y = float(str(a) + "." + str(b))
ddaedalus
  • 131
  • 5
0

If for some reason you don't want to use string concatenation you can do the following:

from math import log10, floor, pow

c = a + (b/(pow(10, floor(log10(b) + 1))))

Not sure if it is any more efficient. You can also import from numpy or import all of either numpy or math:

import numpy

c = a + (b / (numpy.power(10, numpy.floor(numpy.log10(b) + 1))))
kaan_a
  • 3,503
  • 1
  • 28
  • 52
  • Surprisingly enough (for me at least), this is actually more efficient. Checked with `timeit` and was faster than the simple string concatenation. Less readable that's for sure... – Tomerikoo May 20 '20 at 14:23
  • @Tomerikoo FYI there is no difference between floor(...)+1 and floor(...+1) except in the very unusal edge case where the result of ... is so large that adding 1 would cause an overflow which if I'm not mistaken is around 2^1023, which is roughly 9*10^308, not really relevant in most situations – kaan_a May 20 '20 at 14:57
  • Python ints are not limited to `2^1024`. And actually it might be the same as `ceil(...)`... – Tomerikoo May 20 '20 at 15:01
  • @Tomerikoo pow returns a float which is limited below 2^1024.As for ceil being the same, just try it. It will work fine for b=123 but it will fail for b=100. – kaan_a May 20 '20 at 15:10
  • @Tomerikoo After further reflection I suppose adding the 1 to the integer might be faster than adding it to the float though. Then again, maybe not – kaan_a May 20 '20 at 15:12
  • Oh I see now your point with `b=100`! Interesting. And you're right about the overflow, we are dealing with floats... Anyway, I found it interesting that this was actually faster than the obvious string concat – Tomerikoo May 20 '20 at 15:17