简体   繁体   中英

Round a float to same decimals as the multiplier

I'd like someone's help in writing this in the most pythonic way possible

x = 2.651
y = 1.05
a = x * y
print(a)
2.78355

In this example, I want a to have the same number of decimals as x , so the answer should be 2.784. What is a pythonic way to get to this answer with the right number of decimals?

Try something like this. My trick uses string properties.

x = 2.651
y = 1.05

x_dec = len(str(x).split('.')[1])

a = ('{0:.%df}' % x_dec).format(x * y)
x = 2.651
decloc = (str(x).find('.'))+1
decimals = (len(str(x)[decloc:]))
y = 1.05
a = x * y
print(round(a, decimals))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM