#!/usr/bin/env python
"""
rounding sampled for FixedPoint

This module demonstrates the options availoable for controlling rounding
in FixedPoint
"""

__copyright__ = "Copyright (C) Python Software Foundation"
__author__ = "Downright Software Collective"
__version__ = 0, 0, 1

import unittest
from fixedpoint import FixedPoint, bankersRounding, addHalfAndChop

FORMAT = "FixedPoint(%s, 0) = %s"

def testFunction(s):
    print FORMAT % (s, FixedPoint(s, 0))

SAMPLE_DATA = [
    "-4.5", "-3.5", "-2.5", "-1.5", "-0.5", "0.5", "1.5", "2.5", "3.5", "4.5"
    ]

print "Banker's Rounding"
FixedPoint.round = bankersRounding

map(testFunction, SAMPLE_DATA)

print
print

print "Round Away from Zero (add half and chop)"
FixedPoint.round = addHalfAndChop

map(testFunction, SAMPLE_DATA)

print
print

print "Developer defined rounding -- truncate"

def truncate(self, dividend, divisor, quotient, remainder):
    """Don't round: truncate"""
    # The behavior of divmod on a negative divisor is surprising to me.
    # This produces what I mean by truncation: just drop the decimal.
    if quotient < 0 and remainder > 0:
        quotient += 1
    return quotient

FixedPoint.round = truncate

map(testFunction, SAMPLE_DATA)


