Skip to content

Instantly share code, notes, and snippets.

@jackiekazil
jackiekazil / rounding_decimals.md
Last active January 17, 2024 12:29
How do I round to 2 decimals in python?

How do I round to 2 decimals?

In python, you have floats and decimals that can be rounded. If you care about the accuracy of rounding, use decimal type. If you use floats, you will have issues with accuracy.

All the examples use demical types, except for the original value, which is automatically casted as a float.

To set the context of what we are working with, let's start with an original value.

Original Value

@puffin
puffin / MockResponse.py
Created May 11, 2011 18:18
Mock urllib2.open for UnitTest
class MockResponse(object):
def __init__(self, resp_data, code=200, msg='OK'):
self.resp_data = resp_data
self.code = code
self.msg = msg
self.headers = {'content-type': 'text/plain; charset=utf-8'}
def read(self):
return self.resp_data