[Tutor] Dynamic decimal size

Gregor Lingl glingl@aon.at
Wed Mar 5 19:07:01 2003


pan schrieb:

> I am trying to code a numeric class in which some float numbers,
> like 4.25790321, will be stored with varying decimal sizes as:
>
> 4.25790 (decimal size = 5)
> 4.257 (decimal size = 3)
> 4.1 (decimal size =1)
>
> depending on an attribute self.decimalSize set by the users.
>
> I learned that the decimal size can be set as follows:
>
> float('%.3f' %n) <== converting to string representation with
> decimal size = 3 then converting back to float
>
> But it seems to be impossible to set it dynamically:
>
> float('%.%if' %(i,n))
> float('%.(%i)f' %(i,n))
>
> both failed.
>
> I can find a detour by
>
> [1] multiplying by 1000 (if the required decimal size =3)
> [2] then devided by 1000.0
>
> but it seems to be too tedious to me.
>
> Any better way to achieve this?

Yes you can do this by using the *-notation:

>>> f = 0.123456789
>>> for i in range(10):
print "%.*f" % (i,f)


0
0.1
0.12
0.123
0.1235
0.12346
0.123457
0.1234568
0.12345679
0.123456789
>>>

The corresponding docs are here:
I:\Python22\Doc\lib\typesseq-strings.html

Regards, Gregor


>
> Thx in advance
>
> Sincerely,
> pan
>
> ======================
> ~~~~~ be shapeless ~~~~~
>
> Runsun Pan, PhD
> Dept. of Ecology & Evolution
> U. of Chicago, USA
> ======================