blue-sky
blue-sky

Reputation: 53916

Rounding floats in array not working to > 2 significant digits

An array of strings :

values = []
values.append('49.189999')
values.append('48.360001')

Then I convert to float and attempt to round to 4 decimal places :

roundedValues = []  
for v in values : 
    roundedValues.append(round(float(v) , 4))

roundedValues

But values are just rounded to two decimal places :

[49.19, 48.36]

As I'm rounding the float value with 4 parameter, the number of digits rounded to should be 4 instead of 2 ?

Printing the values print(float(v)) returns

49.189999
48.360001

Upvotes: 0

Views: 49

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799310

round() keeps the type as float, which means that both leading 0s left of the decimal point and trailing 0s to the right are not shown when the value is printed. If you need them to be retained then you will need to change the type.

>>> ['{:.4f}'.format(round(float(v), 4)) for v in values]
['49.1900', '48.3600']

Upvotes: 4

Related Questions