DonkeyKong DonkeyKong - 1 year ago 104
Python Question

Force numbers in list to two decimal places

I have a list of numerical data read from a GIS file (.shp):

dataList = [4.98, 5.09, 5.23, 5.35, 5.4, 5.59, ...]

I'm looking for a method that forces numbers in this list to display to two decimal places, with output like this:

dataList = [4.98, 5.09, 5.23, 5.35, 5.40, 5.59, ...]

The main issue is I'm displaying each item in a separate map document in a loop with the following:
TextElement11.text = dataList[count]
which does not support the
solutions I have found elsewhere.

The items in this list are for display purposes only, so it does not matter if a solution requires a conversion e.g. to a string.

I'm using Python 2.7.

Answer Source

Iterate through your datalist and convert each value to the formatted string:

new_datalist = ["{:.2f}".format(value) for value in dataList]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download