Re: elementtree and rounding questions

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gabriel Genellina

    Re: elementtree and rounding questions

    En Wed, 30 Jul 2008 00:56:55 -0300, <jyoung79@kc.rr .comescribi�:
    One other question I had was about rounding floats. I was first looking
    at this syntax to round out to 6 decimal places if needed:
    >
    >>>f = '508.5'
    >>>x = '%.6f' % (float(f)/72)
    >>>x
    '7.062500'
    >
    However, in this instance I don't want the last 2 zeroes. So would it
    be better to do something like this:
    >
    >>f = '508.5'
    >>>x = round(float(f)/72, 6)
    >>>x
    7.0625
    >
    I've been reading a bit about some rounding bugs, but am really not that
    knowledgeable about the subject. Does anyone have a preference of how
    they like to round as well as the result they see?
    If all you need is to *display* the value - use formatting expressions
    like %f, the locale variants, the Template class, or whatever.

    If you want to *compute* something using the rounded value, use the
    round/ceil/floor functions, or perhaps consider using the Decimal class
    depending on your needs.

    From the above, looks like you want to display the value using up to six
    decimal places, avoiding right zeroes. So you just want to strip '0'
    characters from the right side:

    pyf = '508.5'
    pyx = '%.6f' % (float(f)/72)
    pyx
    '7.062500'
    pyx.rstrip('0')
    '7.0625'

    --
    Gabriel Genellina

Working...