float formatting

Dave Hansen iddw at hotmail.com
Wed Jan 25 20:57:55 CET 2006


On 25 Jan 2006 11:32:27 -0800 in comp.lang.python, "Brian"
<bnblazer at gmail.com> wrote:

>Hello all,
>
>I am a bit stuck with a float formatting issue.  What I want to do is
>print a float to the screen with each line showing one more decimal
>place.  Here is a code snip that may explain it better:
>
>#!/usr/bin/env python
>
>num1 = 32
>num2 = 42.98765
>
>for i in range(2,7):
>	print "|" + "%10.3f" % num2 + "|"
>
>In the for loop, is the line with my difficulty.  In a perfect world it
>would read something like this:
>
>for i in range(2,7):
>    print "|" + "%10.if" % num2 + "|"  #where i would be the iteration
>and the num of decimal places
>

Try something like this

>>> num2 = 42.98765
>>> for i in range(2,7):
	print "|" + "%10.*f"%(i,num2) + "|"

	
|     42.99|
|    42.988|
|   42.9877|
|  42.98765|
| 42.987650|
>>> 

HTH,
                                        -=Dave

-- 
Change is inevitable, progress is not.



More information about the Python-list mailing list