[Tutor] how to specify floating point precision from another variable?

Gregor Lingl glingl@aon.at
Sun Jul 13 04:35:01 2003


Thomas CLive Richards schrieb:

>hey,
>
>how can i print out floating point numbers with a precision specified by
>the user?
>
>to print it out normally, I'm doing this:
>
>self.outtxt.AppendText("%s %f\n"% (str(command), arg))
>
>where arg is a floating point number.
>
>however, the user can select to have the floating point numbers print
>out to a precision of their choosing. this number is stored in
>config.floatplaces (as an integer number).
>  
>
This can be done as follows:

 >>> "%s %10.*f" % ("A STRING", input("Dezimals: "), 0.123456789)
Dezimals: 2
'A STRING       0.12'
 >>> "%s %10.*f" % ("A STRING", input("Dezimals: "), 0.123456789)
Dezimals: 7
'A STRING  0.1234568'
 >>> config_floatplaces = int(raw_input("What precision do you want? "))
What precision do you want? 4
 >>> "%s %10.*f" % ("A STRING", config_floatplaces, 0.123456789)
'A STRING     0.1235'
 >>>

A description of how this has to be done you can find at

http://www.python.org/doc/current/lib/typesseq-strings.html

See especially the numbered paragraph 4.

Regards, Gregor