#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    13
    Rep Power
    0

    Round float point nums on list


    I have a list that I can't figure out how to round the float pt numbers to 2 decimal places. Notice these are not float strings but numerics.

    A portion of the list is as follows:

    [-1.47, 5.5300000000000002, 4.21, 4.0999999999999996, 0.94999999999999996, ....

    I've googled and tried several diff ways but none seem to work.

    Any ideas?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    Code:
    >>> round(0.1234, 2)
    0.12
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,709
    Rep Power
    480
    Code:
    >>> def Round(value,nearest):
    ...     return nearest*round(value/float(nearest))
    ... 
    >>> Round(3.14,0.25)
    3.25
    >>>
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    13
    Rep Power
    0
    Originally Posted by Nyktos
    Code:
    >>> round(0.1234, 2)
    0.12
    In pywin I make the following entries, where am I going wrong?

    >>> round(0.1234, 2)
    0.12
    >>> x = 9.1234
    >>> round(x, 2)
    9.1199999999999992
    >>> x
    9.1234000000000002
    >>>

    I want x to be 9.12.
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,709
    Rep Power
    480
    The error is in thinking that IEEE floating point numbers can represent any decimal fraction.

    Code:
    lambertdw$ python
    Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
    [GCC 4.7.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> x = 9.1234
    >>> round(x, 2)
    9.12
    However, round for your example number gives the result you expect on my computer system.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo