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


Groups > comp.lang.python > #42332 > unrolled thread

Re: round off to two decimal & return float

Started byPeter Otten <__peter__@web.de>
First post2013-03-30 10:44 +0100
Last post2013-03-30 10:44 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#42332 — Re: round off to two decimal & return float

FromPeter Otten <__peter__@web.de>
Date2013-03-30 10:44 +0100
SubjectRe: round off to two decimal & return float
Message-ID<mailman.3994.1364636626.2939.python-list@python.org>
ஆமாச்சு 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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web