Working with decimals

Seymore4Head Seymore4Head at Hotmail.invalid
Sun Aug 24 11:12:25 EDT 2014


On Sun, 24 Aug 2014 00:04:29 -0700, Larry Hudson <orgnut at yahoo.com>
wrote:

>On 08/23/2014 02:13 PM, Seymore4Head wrote:
>> On Sat, 23 Aug 2014 13:47:20 -0400, Seymore4Head
>>
>> I found this function that I will be saving for later.
>> def make_it_money(number):
>>      import math
>>      return '$' + str(format(math.floor(number * 100) / 100, ',.2f'))
>>
>> (I still need more practice to find out how it does what it does, but
>> I like the end result)
>
>That's total nonsense and overkill!  If you really want to do it with a separate function, using 
>old style:
>
>def make_it_money(number):
>     return '$%.2f' % number
>
>or using new style:
>
>def make_it_money(number):
>     return '${:.2f}'.format(number)
>
>But even these functions are unnecessary.  Use either of these formatting methods directly in 
>the print() statement...
>
>>
>> So I changed the line in question to:
>>   print (repr(count).rjust(3), make_it_money(payment).rjust(13),
>> make_it_money(balance).rjust(14))
>
>print('{:3d} ${:<13.2f} ${:<14.2f}'.format(count, payment, balance))
>
>or
>
>print('%3d $%-13.2f $%-14.2f' % (count, payment, balance))
>
>But please, please, PLEASE first go through a real tutorial, and WORK the examples to fix them 
>in your mind.  Questions like these will all be covered there.  And you'll learn the language as 
>a whole instead of trying to be spoon-fed isolated answers.  It will be well worth your time.
>
>The tutorial on the official Python web site is a good one (of course there are many others)
>
>docs.python.org/3/tutorial/index.html
>
>It does appear that you're using Py3, but in case you're using Py2, change the '3' in that URL 
>to '2'.
>
>(Print formatting is in section 7)
>
>      -=- Larry -=-
>
>PS.  Oops, my bad...  I just double checked my suggestions, which left-justified the values, but 
>I see you want them right-justified (which keeps the decimal points lined up).  This complicates 
>it a bit to keep the dollar-sign butted up against the value, and it makes it necessary to use 
>that make_it_money() function I said was unnecessary.  But it's still unnecessary by using a 
>little different finagling...  Try either of these versions:
>
>print('{:3d} {:>13s} {:>14s}'.format(count,
>         '$' + str(round(payment, 2)), '$' + str(round(balance, 2))))
>
>print('%3d %13s %14s' % (count, '$' + str(round(payment, 2)), '$' + str(round(balance, 2))))
>
I almost moved, but I was looking at the print out again for this one:
print('%3d $%-13.2f $%-14.2f' % (count, payment, balance))

I can't understand why the $%-13.2f is pushed against the first
column, but the $%-14.2f is not.  It seems like the first case ignores
the leading 0s and the second case doesn't not.





More information about the Python-list mailing list