Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement the __round__ function #1

Open
plexluthor81 opened this issue Nov 29, 2022 · 0 comments
Open

Implement the __round__ function #1

plexluthor81 opened this issue Nov 29, 2022 · 0 comments

Comments

@plexluthor81
Copy link

This is a very handy project! I used it as part of a dozenal clock app I wrote, and I needed a round function so that I could show fractional days with limited precision.

I'm not sure that my code is any good (I suspect it might exacerbate numerical errors) but it met my needs, so perhaps you want to include it.

    def __round__(self, ndigits=None):
        if ndigits is None:
            ndigits = 0

        divisor = self.base**-ndigits
        quotient, remainder = divmod(self.value, divisor)
        if remainder/divisor > 0.5:
            quotient = quotient + 1

        dqs = BaseConverter(quotient, digits=self.digits).string
        if ndigits > 0:
            return BaseConverter(dqs[:-ndigits] + '.' + dqs[-ndigits:], digits=self.digits)
        else:
            return BaseConverter(dqs + '0'*-ndigits, digits=self.digits)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant