How do I string format variables that require additional formatting - python

I am doing a project where I have to print a pay summary for someone based off of information like their hours worked and their pay rate, etc. In the print summary, the spacing is very specific to keep the calculations right-aligned under their specified title (except Premium is centered) so I have been using string formatting to input the variables to keep the formatting consistent between test cases. However, there are some variables that require additional formatting, and I was told that I can not have nested braces.
Here is how I coded the formatting:
print(formatted_work_date + '{:>15}'.format(float(hours_worked)) + ' ' + '{:^7}'.format(user_input_line_2_list[1]) + '{:>11}'.format(str(empl_hourly_payrate)) + '{:>16}'.format(str(round(gross_pay, 2))))
And this is the output:
Workdate Hours Premium Rate Gross Pay
12/23/2020 13.3 0% 71.45 950.29
SO the spacing is correct however, the variable hours_worked is supposed to be a float with 2 digits after the decimal(13.30 not just 13.3), so to get the additional zero I had written '{:.2f}'.format(float(hours_worked)), and I don't know how to place those braces into the braces to format it. Hopefully this question makes sense!

Use the format '{:>15.2f}' to specify that the field width is right-aligned ('>'), 15 characters ('15'), and it's formatted as a float with 2 decimal places (.2f).

Related

Remove decimals from a Float column

shocked beyond belief how difficult this is turning out to be. All I can find are suggestions to change the format of the column to 'int' but I need to keep the comma thousand separators and changing the format to int gets rid of them. THEN i can't find anything on how to add comma separators to an int column. any ideas? really is nothing for me to share in addition to above in terms of what i've tried.
Format your floats...in a string format?
my_string = '{:,.0f}'. format(my_number)
E.g.:
x = 1000.00
'{:,.0f}'. format(x)-> 1,000
Which gives you what you want...something you can print with commas. 0f sets to 0 precision. (for how many decimal places)

How does '%.*g' % (6,k) work in python

I have the following piece of code: (Python 2.7)
k = 4535.65463456
out = '%.*g' % (6,k)
print str(out)
Output: 4535.65
I am not able to understand the working of '%.*g' % (6,k). Since I not familiar with this syntax and don't know what this is called, I am not even able to google it. Could someone help me with this?
Thanks in advance.
With C-borrowed syntax "%6g" you're able to tell python to display your float with a maximum of six digits (if the number isn't too large).
It means that if the integer part of the number has 4 digits, it will use the 2 remaining digits to print the most significant decimal part.
Now if we want to make it parametrizable, we have to generate the format string, which isn't very convienient, so Python introduced Parametrized precision in such strings.
'%.*g' % (6,k)
prints k with 6 digits max.
Now you'll be better of the "new" formatting using format, which allows "nested" formatting to generate the outer formatting (so no need for intricate .* syntax):
'{:.{prec}g}'.format(k, prec=6) # courtesy of Dan comment
Here prec isn't even a special keyword, just the parameter name passed as a function keyword. This is like:
'{:6g}'.format(k)
There's an entire website dedicated to python old & new style formats: https://pyformat.info/
(and there's also a newer syntax with Python 3.6 format strings... https://www.python.org/dev/peps/pep-0498/)
out = '%.*g' % (6,k)
that mean it will print the nember after ,6 ; look at '%.' %. = 4535. , that will be printed then '.*g' , * = 6 , the number after the ',' then g = 5 then number after 6

Displaying total amount including money calculations to user

Note: I'm already using decimal.Decimal
What is the best way to perform and display calculations to the end user when you are required to output in the following rough style:
Item - £ 70.10
Item - £ 5.67
Item - £ 10.33
--------------
Total £ 86.10
I was always taught in maths as a kid to not round before your final answer, else you'll lose precision, but in this case if you don't it looks like we have calculation errors. as the calculation behind the display is not the same as the user would do from the numbers displayed to them.
EG:
My app will be doing: 70.1034 + 5.6693 + 10.333333333 = 86.1060333 (86.11 2dp)
My end user will be doing as above: 70.10 + 5.67 + 10.33 = 86.10
Therefore i appear to be incorrect. What is the best way to overcome this? (I mean generally, but python specific methods will help too)
Use the decimal module to get math that works out correctly. You can set it so each value will automatically use two decimal places.
>>> decimal.getcontext().prec = 2
>>> decimal.Decimal(1)/decimal.Decimal(3)
Decimal('0.33')
When you're working with money, it's normal to lose precision at each intermediate calculation.

Need Help on String Formatting

I've written this program in Python 3 that takes a CSV file that finds the min and max death rates for particular states.
I've basically finished the program and it outputs correctly in the shell, but I have a problem:
Different states have different lengths of characters in their names and the spacing does come out correctly, how do I use string formatting to make the strings space evenly regardless of the number of characters printed?
Here is what I have:
print ("\n", "Indicator |", "Min ",
" | Max ")
print ("-----------------------------------------------------------------------------------------------")
This is the output:
It works well for "Minnesota" but for "District of Columbia" it doesn't format evenly.
Any suggestions? Thanks.
Use string formatting as described here: http://docs.python.org/release/3.1.5/library/string.html
e.g.:
print('{:20} | {:20} {:5.2f} | {:20} {:5.2f}'.format(title, states[statemin], minimum, states[statemax], maximum))
Replace 20 with the longest string that will ever occur.
Note that I am assuming that minimum and maximum are floats, if they are strings, you cannot use '{:x.yf}' notation and you could just use {:6} or something like that instead.
{:20} means that 20 characters of space is used for the string, even if it is shorter (it does not truncate when longer). {:5.2f} means that 5 spaces are used for the float, of which 2 are after the decimal point.

Old style python formatting issues

I looking to display numeric data right justified with a forced sign and spaces for the mantissa such that the decimals all align for each column. The new format specifier uses ">" to align, but I'm unable to get something working with the "c style" format.
For example I'm using:
'%+7.2f \n' % (data)
How do I get the alignment? Is this possible with this old style formatting? I'm looking to get the decimal places all aligned up...seems a silly question, but can't seem to get anything other using the .format command.
That will work, you just have to remember that the first number (the 7 in your example) is the total width of the column including all digits before and after the decimal place and the decimal place and the leading +.
>>> for n in (0.12345, 12345.6, 123):
... print '%+9.2f' % (n)
+0.12
+12345.60
+123.00
>>>

Categories

Resources