Floating numbers and str

Fredrik Lundh fredrik at pythonware.com
Wed Nov 9 21:06:07 CET 2005

"Tuvas" <tuvas21 at gmail.com> wrote:

>I would like to limit a floating variable to 4 signifigant digits, when
> running thorugh a str command. Ei,
> x=.13241414515
> y=str(x)+" something here"
> But somehow limiting that to 4 sign. digits. I know that if you use the
> print statement, you can do something like %.4d, but how can I do this
> with converting the number to a string? Thanks!

you mean "%.4g" ?  the % operator is a string operator, and can be used
outside print:

    text = "%.4g" % value

for more details, here's the first google hit for "python string formatting":


but that doesn't make too much sense if you don't know how things work
in C, which is explained here:


here are some examples:

    >>> x=.13241414515
    >>> x
    >>> "%.4f" % x
    >>> "%.4g" % x

    >>> x=5.13241414515
    >>> "%.4f" % x
    >>> "%.4g" % x


More information about the Python-list mailing list