round off to two decimal & return float
__peter__ at web.de
Sat Mar 30 10:44:04 CET 2013
> Consider the scenario,
>>> a = 10
> This returns a string 10.00. But what is the preferred method to retain
> 10.0 (float) as 10.00 (float)?
You can use round() to convert 1.226 to 1.23
>>> round(1.225, 2)
for example, but 10.0 and 10.00 are the same float value -- there's no way
to keep track of the number of digits you want to see.
> I am trying to assign the value to a cell of a spreadsheet, using
> python-xlwt. I would like to have 10.00 as the value that is right
> aligned. With text it is left aligned.
You can pass 10.0 as the cell value and apply a format to the cell:
# adapted from
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Example')
numbers = [10, 1.0/6]
headers = ["raw", "rounded", "formatted", "rounded and formatted"]
style = xlwt.XFStyle()
style.num_format_str = "0.00"
for column, header in enumerate(headers):
worksheet.write(0, column, header)
for row, value in enumerate(numbers, 1):
worksheet.write(row, 0, value)
worksheet.write(row, 1, round(value, 2))
worksheet.write(row, 2, value, style)
worksheet.write(row, 3, round(value, 2), style)
Move over the cells with the cursor in Excel to compare what is displayed
with the actual value.
More information about the Python-list