round off to two decimal & return float

rurpy at yahoo.com rurpy at yahoo.com
Sat Mar 30 13:32:32 EDT 2013


On 03/30/2013 10:41 AM, Dennis Lee Bieber wrote:
> On Sat, 30 Mar 2013 13:22:59 +0530, ??????? <amachu at amachu.me> declaimed
> the following in gmane.comp.python.general:
> 
>> 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)?
>> 
>> 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.
> 
> 	That is a matter of the spreadsheet formatting the floating point to
> some number of decimal places... Internally it is just saving 1.0E1
> (well, actually, it is saving the binary equivalent).
> 
> 	I don't believe xlwt gives access to the formatting controls, does
> it? [...]

It does.

Here is a short example of how to set the numeric formatting
of cells.  There are more example in the xlwt documentation at 
  https://github.com/python-excel/xlwt/tree/master/xlwt/examples

--------
#!/usr/bin/env python2
import xlwt
def main():
    w = xlwt.Workbook()
    ws = w.add_sheet('Sheet1')
    style_money = xlwt.XFStyle()
    style_money.num_format_str = '[$$-409]#,##0.00;[RED]-[$$-409]#,##0.00'
    for row in range(6):
        ws.write(row, 1, 'Test')
        ws.write(row, 2, 3.123456 - row)
        ws.write(row, 3, 3.123456 - row, style_money)
    w.save('test.xls')
if __name__ == '__main__': main()
--------

> You may have to use the win32 extensions an open an instance of
> Excel, then use Excel's library of functions to select the cell and
> change formatting.



More information about the Python-list mailing list