How to round decimal numbers in Python

How to round Decimal numbers with Symmetric Arithmetic Rounding (as described in article “Rounding” on wikipedia.org?.

Rounding can be done with decimal.Decimal object’s quantize method. Use decimal.ROUND_HALF_UP flag to get a Symmetric Arithmetic Rounding.

For example:

>>> from decimal import Decimal, ROUND_HALF_UP
>>> Decimal("234.4535").quantize(Decimal("0.001"), ROUND_HALF_UP)
Decimal("234.454")
>>> Decimal("234.4534").quantize(Decimal("0.001"), ROUND_HALF_UP)
Decimal("234.453")
>>> Decimal("-234.4535").quantize(Decimal("0.001"), ROUND_HALF_UP)
Decimal("-234.454")
>>> Decimal("-234.4535").quantize(Decimal("0.001"), ROUND_HALF_UP)
Decimal("-234.454")

So, the “traditional” round function will look like this:

from decimal import Decimal, ROUND_HALF_UP

def round(d, digits=0):
    """
    Symmetric Arithmetic Rounding for decimal numbers

    d       - Decimal number to round
    digits  - number of digits after the point to leave

    For example:
    >>> round(Decimal("234.4536"), 3)
    Decimal("234.454")
    >>> round(Decimal("234.4535"), 3)
    Decimal("234.454")
    >>> round(Decimal("234.4534"), 3)
    Decimal("234.453")
    >>> round(Decimal("-234.4535"), 3)
    Decimal("-234.454")
    >>> round(Decimal("234.4535"), -1)
    Decimal("2.3E+2")
    """
    return d.quantize(Decimal("1") / (Decimal('10') ** digits), ROUND_HALF_UP) 

Tags: , ,

9 Responses to “How to round decimal numbers in Python”

  1. evie Says:

    i dont get it!!! HELP

  2. ken Says:

    Thanks, it works!

  3. KEITH Says:

    < blockquote >< a href=”http://cheaptabletsonline.com/”>CheapTabletsOnline.com. Canadian Health&Care.Special Internet Prices.Best quality drugs.No prescription online pharmacy. High quality drugs. Buy drugs online< /a >…

    Buy:Human Growth Hormone.Prednisolone.Accutane.Prevacid.Lumigan.100% Pure Okinawan Coral Calcium.Actos.Retin-A.Valtrex.Zyban.Mega Hoodia.Nexium.Petcam (Metacam) Oral Suspension.Arimidex.Synthroid.Zovirax….

  4. oxygen Says:

    oxygen http://nzq.4xs.ii88.vg : sensor…

    oxygen…

  5. GET THE HOTTEST REVIEWS ON ALL OF THE LATEST GADGETS OUT!! Says:

    WWW.INSPECTAGADGETS.COM…

    YOUTUBE VIDEO REVIEWS ON THE HOTTEST ELECTRONICS OUT

  6. REVIEW IT BEFORE YOU BUY IT!!! Says:

    MOST INFORMATIVE SITE FOR ELECTRONICS….

    YOUTUBE VIDEO REVIEWS ON THE HOTTEST ELECTRONICS OUT

  7. IPAD 2 REVIEW Says:

    iPAD 2 REVIEW!!!…

    NEW iPAD 2 REVIEWFIND OUT WHAT PEOPLE ARE SAYING!!…

  8. IPAD 2 REVIEWS Says:

    iPAD 2 REVIEW!!!…

    iPAD 2 LATEST REVIEWSFIND OUT WHAT PEOPLE ARE SAYING!!…

  9. Alexander7 Says:

    < b >< a href=”http://www.trustedpillspot.com/?ml=buy-generic-LEVITRA buy@generic.LEVITRA” >…< /a >< /b >< /blockquote >…

    Need cheap generic LEVITRA?…

Leave a Reply