Designing more useful rounding

We truncated the presentation on rounding. We defined the required functions for round() and trunc() without further explanation. These definitions are the minimum requirements of the abstract superclass. However, these definitions are not quite enough for our purposes.

To process currency, we'll often have code that looks like this:

>>> price = FixedPoint(1299, 100) 
>>> tax_rate = FixedPoint(725, 1000) 
>>> price * tax_rate 
FixedPoint(941775, scale=100000) 

Then, we need to round this value to a scale of 100 to get a value of 942. We need methods that will round (as well as truncate) a number to a new scale factor. The following is a method to round to a specific scale:

def round_to(self, new_scale: int) -> 'FixedPoint':
f = new_scale / self.scale
return FixedPoint(int(self.value * f + .5), scale=new_scale)

The following code allows us to properly rescale the value:

>>> price = FixedPoint(1299, 100) 
>>> tax_rate = FixedPoint(725, 1000) 
>>> tax = price * tax_rate 
>>> tax.round_to(100) 
FixedPoint(942, scale=100) 

This shows that we have a minimal set of functions to calculate currency.

In the next section, we'll see how to implement other special methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset