I’m Embarrassed!

October 4, 2016

Matthew Arcus pointed out a bug in my solution to the previous problem:

> (dollar 1234567.9999)
$1,234,567.100

I can’t remember a similarly bad bug in any previous Programming Praxis problem.

You get the day off today. There is no exercise for you to do. You are welcome to read or run my corrected solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

2 Responses to “I’m Embarrassed!”

  1. Alex B said

    Updated my python solution so it rounds instead of truncating.

    def dollars(n):
        '''Format a number as a dollar amount string'''
        n = n*100
        if n % 1 >= 0.5:
            n = int(n) + 1
        else:
            n = int(n)
        s = str(n)
        i, d = s[:-2], s[-2:]
        l = [i[(c-3 if c >= 3 else 0):c] for c in range(len(i),0,-3)]
        o = '.'.join((','.join(reversed(l)),d))
        return ''.join(('$', o))
    
    >>> dollars(1234567.9999)
    '$1,234,568.00'
    >>> dollars(1234567.9950)
    '$1,234,568.00'
    >>> dollars(1234567.9949)
    '$1,234,567.99'
    >>> dollars(1234567.9900)
    '$1,234,567.99'
    >>> dollars(1234567.949)
    '$1,234,567.95'
    >>> dollars(1234567)
    '$1,234,567.00'
    
  2. matthew said

    Sorry about that. I find it’s easy to get these simple problems wrong, just by not paying enough attention. New solution looks good anyway.

Leave a comment