float to string with different precision

Roger Miller roger.miller at nova-sol.com
Fri Aug 10 19:15:51 EDT 2007


On Aug 10, 8:37 am, Zentrader <zentrad... at gmail.com> wrote:
>
> If the above does not work
> [/code]test_list = [ 5.32, 10.35634, 289.234 ]
> for num in test_list :
>    str_num = "%11.5f" % (num)       ## expand to at least 5
>    print str_num, "-->", str_num.strip()[:5][/code]

This has the disadvantage that it doesn't round the last digit.  For
example 10.356634 yields 10.356 instead of 10.357.

You can use '*' in format strings to take a numeric field value from a
variable.  For example

   ndecimals = 2
   print "%5.*f" % (ndecimals, x)

formats x with 2 digits following the decimal point.  Or you can
simply
cobble up a format string at run time:

   format = "%%5.%df" % ndecimals
   print format % x




More information about the Python-list mailing list