<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html" rel="noreferrer">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p>

<pre><code>n = 5.59
round(n, 1) # 5.6
</code></pre>

<p>But, in actuality, good old floating point weirdness creeps in and you get:</p>

<pre><code>5.5999999999999996
</code></pre>

<p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html" rel="noreferrer">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html" rel="noreferrer">See here also</a>.</p>

<p>Short of creating my own round library, is there any way around this?</p>

[{'answer_id': 56832, 'author': 'ima', 'author_id': 5733, 'author_profile': 'https://Stackoverflow.com/users/5733', 'pm_score': -1, 'selected': False, 'text': '<p>What about:</p>\n\n<pre><code>round(n,1)+epsilon\n</code></pre>\n'}, {'answer_id': 56833, 'author': 'Jimmy', 'author_id': 4435, 'author_profile': 'https://Stackoverflow.com/users/4435', 'pm_score': 8, 'selected': True, 'text': "<p>I can't help the way it's stored, but at least formatting works correctly: </p>\n\n<pre><code>'%.1f' % round(n, 1) # Gives you '5.6'\n</code></pre>\n"}, {'answer_id': 56840, 'author': 'Frank Krueger', 'author_id': 338, 'author_profile': 'https://Stackoverflow.com/users/338', 'pm_score': 4, 'selected': False, 'text': '<p>You can switch the data type to an integer:</p>\n\n<pre><code>&gt;&gt;&gt; n = 5.59\n&gt;&gt;&gt; int(n * 10) / 10.0\n5.5\n&gt;&gt;&gt; int(n * 10 + 0.5)\n56\n</code></pre>\n\n<p>And then display the number by inserting the locale\'s decimal separator.</p>\n\n<p>However, <a href="https://stackoverflow.com/questions/56820/round-in-python-doesnt-seem-to-be-rounding-properly#56833">Jimmy\'s answer</a> is better.</p>\n'}, {'answer_id': 56841, 'author': 'nlucaroni', 'author_id': 157, 'author_profile': 'https://Stackoverflow.com/users/157', 'pm_score': 2, 'selected': False, 'text': '<p>You can use the string format operator <code>%</code>, similar to sprintf.</p>\n\n<pre><code>mystring = "%.2f" % 5.5999\n</code></pre>\n'}, {'answer_id': 56844, 'author': 'Tomi Kyöstilä', 'author_id': 616, 'author_profile': 'https://Stackoverflow.com/users/616', 'pm_score': 4, 'selected': False, 'text': "<p>You get '5.6' if you do <code>str(round(n, 1))</code> instead of just <code>round(n, 1)</code>.</p>\n"}, {'answer_id': 56845, 'author': 'spoulson', 'author_id': 3347, 'author_profile': 'https://Stackoverflow.com/users/3347', 'pm_score': 3, 'selected': False, 'text': '<p>Floating point math is vulnerable to slight, but annoying, precision inaccuracies.  If you can work with integer or fixed point, you will be guaranteed precision.</p>\n'}, {'answer_id': 56849, 'author': 'Jason Navarrete', 'author_id': 3920, 'author_profile': 'https://Stackoverflow.com/users/3920', 'pm_score': 2, 'selected': False, 'text': "<p><strong>printf</strong> the sucker.</p>\n\n<pre><code>print '%.1f' % 5.59  # returns 5.6\n</code></pre>\n"}, {'answer_id': 56850, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 7, 'selected': False, 'text': '<p>Formatting works correctly even without having to round:</p>\n\n<pre><code>"%.1f" % n\n</code></pre>\n'}, {'answer_id': 57704, 'author': 'Will Harris', 'author_id': 4702, 'author_profile': 'https://Stackoverflow.com/users/4702', 'pm_score': 5, 'selected': False, 'text': '<p><code>round(5.59, 1)</code> is working fine. The problem is that 5.6 cannot be represented exactly in binary floating point.</p>\n\n<pre><code>&gt;&gt;&gt; 5.6\n5.5999999999999996\n&gt;&gt;&gt; \n</code></pre>\n\n<p>As Vinko says, you can use string formatting to do rounding for display.</p>\n\n<p>Python has a <a href="http://docs.python.org/lib/module-decimal.html" rel="noreferrer">module for decimal arithmetic</a> if you need that.</p>\n'}, {'answer_id': 3225829, 'author': 'Jesse Dhillon', 'author_id': 328501, 'author_profile': 'https://Stackoverflow.com/users/328501', 'pm_score': 3, 'selected': False, 'text': '<p>Take a look at the <a href="http://docs.python.org/library/decimal.html" rel="noreferrer">Decimal module</a></p>\n\n<blockquote>\n  <p>Decimal “is based on a floating-point\n  model which was designed with people\n  in mind, and necessarily has a\n  paramount guiding principle –\n  computers must provide an arithmetic\n  that works in the same way as the\n  arithmetic that people learn at\n  school.” – excerpt from the decimal\n  arithmetic specification.</p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n  <p>Decimal numbers can be represented\n  exactly. In contrast, numbers like 1.1\n  and 2.2 do not have an exact\n  representations in binary floating\n  point. End users typically would not\n  expect 1.1 +  2.2 to display as\n  3.3000000000000003  as it does with binary floating point.</p>\n</blockquote>\n\n<p>Decimal provides the kind of operations that make it easy to write apps that require floating point operations and <em>also</em> need to present those results in a human readable format, e.g., accounting.</p>\n'}, {'answer_id': 15398691, 'author': 'Robert Griesmeyer', 'author_id': 2070300, 'author_profile': 'https://Stackoverflow.com/users/2070300', 'pm_score': 5, 'selected': False, 'text': "<p>If you use the Decimal module you can approximate without the use of the 'round' function.  Here is what I've been using for rounding especially when writing monetary applications:</p>\n<pre><code>from decimal import Decimal, ROUND_UP\n\nDecimal(str(16.2)).quantize(Decimal('.01'), rounding=ROUND_UP)\n</code></pre>\n<p>This will return a Decimal Number which is 16.20.</p>\n"}, {'answer_id': 17296776, 'author': 'Alexandre Lymberopoulos', 'author_id': 2519948, 'author_profile': 'https://Stackoverflow.com/users/2519948', 'pm_score': 3, 'selected': False, 'text': '<p>It\'s a big problem indeed. Try out this code:</p>\n\n<pre><code>print "%.2f" % (round((2*4.4+3*5.6+3*4.4)/8,2),)\n</code></pre>\n\n<p>It displays 4.85. Then you do: </p>\n\n<pre><code>print "Media = %.1f" % (round((2*4.4+3*5.6+3*4.4)/8,1),)\n</code></pre>\n\n<p>and it shows 4.8. Do you calculations by hand the exact answer is 4.85, but if you try: </p>\n\n<pre><code>print "Media = %.20f" % (round((2*4.4+3*5.6+3*4.4)/8,20),)\n</code></pre>\n\n<p>you can see the truth: the float point is stored as the nearest finite sum of fractions whose denominators are powers of two.</p>\n'}, {'answer_id': 33771679, 'author': 'Станислав Повышев', 'author_id': 2491847, 'author_profile': 'https://Stackoverflow.com/users/2491847', 'pm_score': 2, 'selected': False, 'text': "<p>Works Perfect </p>\n\n<pre><code>format(5.59, '.1f') # to display\nfloat(format(5.59, '.1f')) #to round\n</code></pre>\n"}, {'answer_id': 42443001, 'author': 'Gildas', 'author_id': 5318186, 'author_profile': 'https://Stackoverflow.com/users/5318186', 'pm_score': 2, 'selected': False, 'text': '<p>I am doing:</p>\n\n<pre><code>int(round( x , 0))\n</code></pre>\n\n<p>In this case, we first round properly at the unit level, then we convert to integer to avoid printing a float.</p>\n\n<p>so </p>\n\n<pre><code>&gt;&gt;&gt; int(round(5.59,0))\n6\n</code></pre>\n\n<p>I think this answer works better than formating the string, and it also makes more sens to me to use the round function.</p>\n'}, {'answer_id': 48918096, 'author': 'Gregory Pittman', 'author_id': 9393856, 'author_profile': 'https://Stackoverflow.com/users/9393856', 'pm_score': 0, 'selected': False, 'text': '<p>Here\'s where I see round failing. What if you wanted to round these 2 numbers to one decimal place?\n23.45\n23.55\nMy education was that from rounding these you should get:\n23.4\n23.6\nthe "rule" being that you should round up if the preceding number was odd, not round up if the preceding number were even.\nThe round function in python simply truncates the 5.</p>\n'}, {'answer_id': 49164892, 'author': 'Dondon Jie', 'author_id': 7866170, 'author_profile': 'https://Stackoverflow.com/users/7866170', 'pm_score': 1, 'selected': False, 'text': "<p>Code:</p>\n\n<pre><code>x1 = 5.63\nx2 = 5.65\nprint(float('%.2f' % round(x1,1)))  # gives you '5.6'\nprint(float('%.2f' % round(x2,1)))  # gives you '5.7'\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>5.6\n5.7\n</code></pre>\n"}, {'answer_id': 49777226, 'author': 'Syed Is Saqlain', 'author_id': 5280048, 'author_profile': 'https://Stackoverflow.com/users/5280048', 'pm_score': 1, 'selected': False, 'text': '<p>The problem is only when last digit is 5. Eg. 0.045 is internally stored as 0.044999999999999... You could simply increment last digit to 6 and round off. This will give you the desired results.</p>\n\n<pre><code>import re\n\n\ndef custom_round(num, precision=0):\n    # Get the type of given number\n    type_num = type(num)\n    # If the given type is not a valid number type, raise TypeError\n    if type_num not in [int, float, Decimal]:\n        raise TypeError("type {} doesn\'t define __round__ method".format(type_num.__name__))\n    # If passed number is int, there is no rounding off.\n    if type_num == int:\n        return num\n    # Convert number to string.\n    str_num = str(num).lower()\n    # We will remove negative context from the number and add it back in the end\n    negative_number = False\n    if num &lt; 0:\n        negative_number = True\n        str_num = str_num[1:]\n    # If number is in format 1e-12 or 2e+13, we have to convert it to\n    # to a string in standard decimal notation.\n    if \'e-\' in str_num:\n        # For 1.23e-7, e_power = 7\n        e_power = int(re.findall(\'e-[0-9]+\', str_num)[0][2:])\n        # For 1.23e-7, number = 123\n        number = \'\'.join(str_num.split(\'e-\')[0].split(\'.\'))\n        zeros = \'\'\n        # Number of zeros = e_power - 1 = 6\n        for i in range(e_power - 1):\n            zeros = zeros + \'0\'\n        # Scientific notation 1.23e-7 in regular decimal = 0.000000123\n        str_num = \'0.\' + zeros + number\n    if \'e+\' in str_num:\n        # For 1.23e+7, e_power = 7\n        e_power = int(re.findall(\'e\\+[0-9]+\', str_num)[0][2:])\n        # For 1.23e+7, number_characteristic = 1\n        # characteristic is number left of decimal point.\n        number_characteristic = str_num.split(\'e+\')[0].split(\'.\')[0]\n        # For 1.23e+7, number_mantissa = 23\n        # mantissa is number right of decimal point.\n        number_mantissa = str_num.split(\'e+\')[0].split(\'.\')[1]\n        # For 1.23e+7, number = 123\n        number = number_characteristic + number_mantissa\n        zeros = \'\'\n        # Eg: for this condition = 1.23e+7\n        if e_power &gt;= len(number_mantissa):\n            # Number of zeros = e_power - mantissa length = 5\n            for i in range(e_power - len(number_mantissa)):\n                zeros = zeros + \'0\'\n            # Scientific notation 1.23e+7 in regular decimal = 12300000.0\n            str_num = number + zeros + \'.0\'\n        # Eg: for this condition = 1.23e+1\n        if e_power &lt; len(number_mantissa):\n            # In this case, we only need to shift the decimal e_power digits to the right\n            # So we just copy the digits from mantissa to characteristic and then remove\n            # them from mantissa.\n            for i in range(e_power):\n                number_characteristic = number_characteristic + number_mantissa[i]\n            number_mantissa = number_mantissa[i:]\n            # Scientific notation 1.23e+1 in regular decimal = 12.3\n            str_num = number_characteristic + \'.\' + number_mantissa\n    # characteristic is number left of decimal point.\n    characteristic_part = str_num.split(\'.\')[0]\n    # mantissa is number right of decimal point.\n    mantissa_part = str_num.split(\'.\')[1]\n    # If number is supposed to be rounded to whole number,\n    # check first decimal digit. If more than 5, return\n    # characteristic + 1 else return characteristic\n    if precision == 0:\n        if mantissa_part and int(mantissa_part[0]) &gt;= 5:\n            return type_num(int(characteristic_part) + 1)\n        return type_num(characteristic_part)\n    # Get the precision of the given number.\n    num_precision = len(mantissa_part)\n    # Rounding off is done only if number precision is\n    # greater than requested precision\n    if num_precision &lt;= precision:\n        return num\n    # Replace the last \'5\' with 6 so that rounding off returns desired results\n    if str_num[-1] == \'5\':\n        str_num = re.sub(\'5$\', \'6\', str_num)\n    result = round(type_num(str_num), precision)\n    # If the number was negative, add negative context back\n    if negative_number:\n        result = result * -1\n    return result\n</code></pre>\n'}, {'answer_id': 60294994, 'author': 'Tali Oat', 'author_id': 4609659, 'author_profile': 'https://Stackoverflow.com/users/4609659', 'pm_score': 2, 'selected': False, 'text': '<p>I would avoid relying on <code>round()</code> at all in this case. Consider</p>\n\n<pre><code>print(round(61.295, 2))\nprint(round(1.295, 2))\n</code></pre>\n\n<p>will output</p>\n\n<pre><code>61.3\n1.29\n</code></pre>\n\n<p>which is not a desired output if you need solid rounding to the nearest integer. To bypass this behavior go with <code>math.ceil()</code> (or <code>math.floor()</code> if you want to round down):</p>\n\n<pre><code>from math import ceil\ndecimal_count = 2\nprint(ceil(61.295 * 10 ** decimal_count) / 10 ** decimal_count)\nprint(ceil(1.295 * 10 ** decimal_count) / 10 ** decimal_count)\n</code></pre>\n\n<p>outputs</p>\n\n<pre><code>61.3\n1.3\n</code></pre>\n\n<p>Hope that helps.</p>\n'}, {'answer_id': 61820474, 'author': 'conmak', 'author_id': 12014156, 'author_profile': 'https://Stackoverflow.com/users/12014156', 'pm_score': 2, 'selected': False, 'text': '<p>Another potential option is:</p>\n\n<pre><code>def hard_round(number, decimal_places=0):\n    """\n    Function:\n    - Rounds a float value to a specified number of decimal places\n    - Fixes issues with floating point binary approximation rounding in python\n    Requires:\n    - `number`:\n        - Type: int|float\n        - What: The number to round\n    Optional:\n    - `decimal_places`:\n        - Type: int \n        - What: The number of decimal places to round to\n        - Default: 0\n    Example:\n    ```\n    hard_round(5.6,1)\n    ```\n    """\n    return int(number*(10**decimal_places)+0.5)/(10**decimal_places)\n</code></pre>\n'}, {'answer_id': 65786552, 'author': 'Irfan wani', 'author_id': 13789135, 'author_profile': 'https://Stackoverflow.com/users/13789135', 'pm_score': 0, 'selected': False, 'text': '<p>Here is an easy way to round a float number to any number of decimal places, and it still works in 2021!</p>\n<pre><code>float_number = 12.234325335563\nrounded = round(float_number, 3) # 3 is the number of decimal places to be returned.You can pass any number in place of 3 depending on how many decimal places you want to return.\nprint(rounded)\n</code></pre>\n<p>And this will print;</p>\n<pre><code>12.234\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/56820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/736/']