简体   繁体   English

计算后最有效的Python方法

[英]Most Pythonic Way To Round a Float After Calculation

Ultimately, I am trying to accomplish the calculation of a number that gives me back 3 decimal places, and round it to 2 decimal places. 最终,我试图完成一个数字的计算,该数字使我返回3个小数位,并将其四舍五入为2个小数位。 What I have, is thus: 因此,我所拥有的是:

total = 175

tax = .0875

total += total * tax  # giving me my desired total
print total
>>> 190.3125

rounded = round(total, 2)  # giving me my desired decimal place
print rounded
>>> 190.31

I was thinking of doing the total and rounded line in one, but it looks jumbled... 我本来想将totalrounded线合二为一,但是看起来很混乱……

Here is what I feel is the fastest way, but does not look as readable as I would like: 我觉得这是最快的方法,但是看起来不像我想要的那样可读:

total = round((total + (total*tax)), 2)

print total
>>> 190.31

EDIT 编辑

Thank you guys for the input in the comments. 谢谢大家在评论中的投入。 It seems time is clearly not something to stress here & I am going to run with rounded = round(total, 2) for my code. 在这里似乎时间显然没什么要紧的,我将为我的代码使用rounded = round(total, 2) Thanks again! 再次感谢!

I think you should first think pythonically. 我认为您应该首先以Python的方式思考。 What is the critical purpose of rounding a float? 四舍五入的关键目的是什么? Do you need to use this rounded float to calculate later or you want to display it? 您是否需要使用此四舍五入的浮点数以便稍后计算或要显示它? Or you want to store it into a file or database with a consistent format? 还是要以一致的格式将其存储到文件或数据库中? Different purposes lead to different methods. 不同的目的导致不同的方法。

If you want to use this rounded float to calculate later, you just don't need to round it. 如果要使用此舍入后的浮点数进行以后的计算,则只需将其舍入即可。 We should not do any additional process before the final calculation as it will only reduce the precision of results without any benefit. 在最终计算之前,我们不应执行任何其他处理,因为这只会降低结果的准确性,而没有任何好处。

If you want to display this rounded float, you can keep the precision inside variable and use string format: print "%.2f" % total . 如果要显示此四舍五入的浮点数,则可以将precision保留在变量内,并使用字符串格式: print "%.2f" % total This will also print out what you want but won't make you lose precision. 这也会打印出您想要的内容,但不会使您失去精度。

If you want to store it into a file or a database, you can just go to rounded = round(total, 2) , it is really pythonic and useful. 如果要将其存储到文件或数据库中,则可以转到rounded = round(total, 2) ,它确实是pythonic且有用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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