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":

    http://docs.python.org/lib/typesseq-strings.html

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

    http://www.cplusplus.com/ref/cstdio/printf.html

here are some examples:

    >>> x=.13241414515
    >>> x
    0.13241414515
    >>> "%.4f" % x
    '0.1324'
    >>> "%.4g" % x
    '0.1324'

    >>> x=5.13241414515
    >>> "%.4f" % x
    '5.1324'
    >>> "%.4g" % x
    '5.132'

</F> 






More information about the Python-list mailing list