Python - The problem of retaining the number of decimal places in numbers
PHP中文网
PHP中文网 2017-05-18 10:52:59
0
1
780

I will perform an operation on each element in [-0.32695389161796801, -0.31471406408825409, -0.31475407980700348] by first retaining 3 digits after the decimal point and then 2 digits after the decimal point, using round(round(-0.32695389161796801,3),2 ) way, I get [-0.33000000000000002, -0.32000000000000001, -0.32000000000000001], but what I want to get is [-0.33, -0.32, -0.32], thank you

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
Peter_Zhu

When using Python to handle floating point numbers where precision is important, it is recommended to use the built-in Decimal library:

from decimal import Decimal
a = Decimal('1.0231212121')
a = round(a,3) # Decimal('1.023')

If you just want it to look "accurate", you can also use the string format method

'{:.2f}'.format(1.0231212121) # '1.02'
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!