Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #42332

Re: round off to two decimal & return float

From Peter Otten <__peter__@web.de>
Subject Re: round off to two decimal & return float
Date 2013-03-30 10:44 +0100
Organization None
References <515699DB.8060104@amachu.me>
Newsgroups comp.lang.python
Message-ID <mailman.3994.1364636626.2939.python-list@python.org> (permalink)

Show all headers | View raw


ஆமாச்சு wrote:

> Consider the scenario,
> 
>>> a = 10
>>> "{0:.2f}".format(a)
> '10.00'
> 
> 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)
1.23

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 
#https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/examples/num_formats.py

import xlwt

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)

workbook.save('tmp.xls')

Move over the cells with the cursor in Excel to compare what is displayed 
with the actual value.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: round off to two decimal & return float Peter Otten <__peter__@web.de> - 2013-03-30 10:44 +0100

csiph-web