I have the following:
strA = '0.8243'
strB = '12.3'
strC = float(strA) + float(strB)
print strC # 13.1243...I want it formatted like that of strB...13.1
strA and strB will change and will have unknown amount of decimal places. However, I always want the decimal places to retain that of strB. Is that possible?
Note: if strB = '12', then float(strB) = 12.0...I want no decimals in this case (e.g. match the original string)
You should use the decimal.Decimal class here, and amend to how you want rounding to occur:
strA = '0.8243'
strB = '12.3'
from decimal import Decimal as D
a, b = map(D, [strA, strB])
print (a + b).quantize(b)
# 13.1
And strB = '12' gives you 13 as a result.
strA = '0.8243'
strB = '12.3'
C = float(strA) + float(strB)
print '{:.{}f}'.format(C, len(strB.partition('.')[2]))
Output
13.1
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