Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy the formatting of a number to another number?

Tags:

python

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)


2 Answers

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.

like image 52
Jon Clements Avatar answered Dec 22 '25 23:12

Jon Clements


strA = '0.8243'
strB = '12.3'
C = float(strA) + float(strB)
print '{:.{}f}'.format(C, len(strB.partition('.')[2]))

Output

13.1
like image 22
thefourtheye Avatar answered Dec 22 '25 22:12

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!