I have a Django Queryset object called data containing string keys and float values.
I want to convert all floats to 2 decimal places.
If I do this:
>>> param1_values = [d[param1] for d in data]
>>> param1_values[:5]
[26.1, 24.6, 26.2444444444444, 27.3103448275862, 26.7576923076923]
…which is fine but I need to float to two decimal places.
However, if I do this:
>>> param1_values = ["%.2f" % d['mean_air_temp'] for d in data]
>>> param1_values[:5]
['26.10', '24.60', '26.24', '27.31', '26.76']
The numbers are what I wanted but they are converted to strings! Why does this occur and how do I solve it?
Any help appreciated.
You can use the built-in
roundfunction:This seems to be accurate enough for your use case. If you need a more precise answer see Ignacio’s response using Decimal.