getting an answer to two decimal places using the int function - python

I am brand new to python, only a week or two into my course. Here is what I have written:
#prompt user for input
purchaseAmount = eval(input("please enter Purchase Amount: "))
# compute sales tax
salesTax = purchaseAmount * 0.06
# display sales tax to two decimal points
print("sales tax is", int(salesTax * 100 / 100.0))
and this is what it returns:
please enter Purchase Amount: 197.55
sales tax is 11
My text suggest I should get the answer 11.85.
What should I change to get 2 decimal places in my answer?

You should use the string formatting mini-language.
>>> salesTax = 22.2
>>> print("sales tax is %0.2f" % salesTax)
sales tax is 22.20
Alternatively use the newer format method
>>> salesTax = 22.256
>>> print("sales tax is {:.2f}".format(salesTax))
sales tax is 22.26

Use float instead:
print("sales tax is", round(float(salesTax * 100 / 100.0),2))
This will print the value to 2 decimal places as 11.85

You're taking int of the whole thing, which will always be an integer. You need to first take the int and then divide the result of the int by 100. So instead of this:
int(salesTax * 100 / 100.0)
Do this:
int(salesTax * 100) / 100.0

Its a minor correction. You could use float to get the exact answer with the decimal point. You will lose precision with int.
purchaseAmount = eval(input("please enter Purchase Amount: "))
salesTax = purchaseAmount * 0.06
# get salesTax in floating point number
salesTax = float(salesTax * 100 / 100.0)
print salesTax
-> 11.853

Related

What changes should I do for the output to display with two decimal places?

I want my output to have a 2 decimal places result. What should I do?
Ideal output is:
Enter the number of plants to purchase: 14
Enter the price per unit of plant: 250.00
The total payable amount is: P3,350.00
n1 = input('Enter number of plants: ')
n2= input('Enter price per unit: ')
mul= float(n1) * float(n2)
mul2= (float(n1)-float(10)) * (float(n2))
mul3 = float(10) * float(n2)
discount2 = float (mul2)* float(0.15)
total2=mul2-discount2
total3= total2+mul3
if float(n1)<=float(10):
mul= float(n1) * float(n2)
print('The total payable amount is: ', mul)
elif float(n1)>float(10):
print('The total payable amount is: ', total3)
A few answers missed the fact you also needed thousands separated by a comma. here is the format command which displays the price the way you expect it
n1 = input('Enter number of plants: ')
n2= input('Enter price per unit: ')
mul= float(n1) * float(n2)
mul2= (float(n1)-float(10)) * (float(n2))
mul3 = float(10) * float(n2)
discount2 = float (mul2)* float(0.15)
total2=mul2-discount2
total3= total2+mul3
if float(n1)<=float(10):
mul= float(n1) * float(n2)
print('The total payable amount is: ${:0,.2f}'.format(mul))
elif float(n1)>float(10):
print('The total payable amount is: ${:0,.2f}'.format(total3))
Use a formatted string. Also, convert the values to floats at the start, then there is no need to keep converting everything.
plants_str = input('Enter number of plants: ')
price_str = input('Enter price per unit: ')
plants = float(plants_str)
price = float(price_str)
total = plants * price
if plants > 10:
total -= 0.15 * (plants - 10) * price
print(f"The total payable amount is: {total:0,.2f}")
But as noted in a comment, for serious applications involving currency you should use the decimal library. This ensures decimal numbers are represented exactly.
from decimal import Decimal
plants_str = input('Enter number of plants: ')
price_str = input('Enter price per unit: ')
plants = Decimal(plants_str)
price = Decimal(price_str)
total = plants * price
if plants > 10:
total -= Decimal("0.15") * (plants - 10) * price
print(f"The total payable amount is: {total:0,.2f}")
You can use the str.format function and I made some small adjustments to your code.
n1 = float(input('Enter number of plants: '))
n2 = float(input('Enter price per unit: '))
mul = n1 * n2
if n1<=10:
print('The total payable amount is: ${:0,.2f}'.format(mul))
else:
print('The total payable amount is: ${:0,.2f}'.format(0.85*mul+1.5*n2))

String format and floating points

I am trying to reach the .17 after zero how to pick two dec after the zero in this case
i tried the old way with % but wanna discover if that possible with the .format anyone can help?
km = float(input('Enter "km" numbers: '))
conv_fac = 0.621371
round(miles,-2)
miles = km * conv_fac
print('{} km is equal to {} miles'.format(km, miles))
Output:
Enter "km" numbers: 3.5
3.5 km is equal to 2.1747985 miles
You can use {:.2f} to format a float with 2 digits after the decimal point:
print('{:.2f} km is equal to {:.2f} miles'.format(km, miles))
You can also use an f-string:
print(f'{km:.2f} km is equal to {miles:.2f} miles')
You don't have to call round before formatting the floats.
Refer to the string formatting docs for more information.
You can round of to two decimal places as you have attempted but you have to give the decimal point as second argument which is 2 and not -2 like below.
km = float(input('Enter "km" numbers: '))
conv_fac = 0.621371
miles = round(km * conv_fac,2)
print('{} km is equal to {} miles'.format(km, miles))

How to work out the percentage of an inputted number?

I've started using python a few days ago and am having difficulty in adding 20% (VAT) of the answer to 'Enter the total cost of the meal'. So, say the user inputted 80, how would I get it to add 20% of the inputted answer (80) to the total cost? Thank you in advance!
quotient = 1 / 5
percentage = quotient * 100
total_cost = float(input('Enter the total cost of the meal: '))
total_cost_vat=total_cost+percentage
print("Total cost of meal inclusive of VAT is",total_cost_vat)
number_of_people = float(input('Enter the number of people paying: '))
var1 = float(input(total_cost_vat / number_of_people))
You first create a variable quotient and you make it equal 1/5 or 0.2.
But now you times it by 100? Why? And then instead of multiplying total_cost_vat you add basically 20 to it. Why?
vat_percentage = 0.2 # In math 0.2 is 20%
subtotal_cost = float(input('Enter the total cost of the meal: '))
# Add 1 to the percentage to get total + vat
total_cost = subtotal_cost * (1 + vat_percentage)
If you know for sure that the tax is going to be 20% every time you calculate the VAT you can just multiply the total cost by 1.2, otherwise you can have the tax as a variable in decimal form. Then you multiply the pre tax cost by 1 + the tax.
tax = 0.20
pre_tax = float(input('Enter the total cost of the meal: '))
total_cost_vat = pre_tax * (1 + tax)
print("Total cost of meal inclusive of VAT is",total_cost_vat)
number_of_people = float(input('Enter the number of people paying: '))
print(total_cost_vat / number_of_people)
I coded it up below and annotated it. Some of the code you had wasn't necessary.
If you don't know that it is always going to be 20% you can use the below code and change the value of the variable:
# step 1: simpler than 1/5
percentage = 0.2
# step 2: getting input
total_cost = float(input('Enter the total cost of the meal: '))
# step 3: calculating the cost with the vat
total_cost_vat = total_cost + (percentage * total_cost)
# step 4: printing our value
print(total_cost_vat) # printing vat value
If you do know the value of the vat you can replace step 3 with below code:
total_cost_vat = 1.2 * total_cost
Hope this helped!

Rounding number up using .format()

I’m writing a simple program and I’m using .format() to round the number to 2 d.p.
State = 0.05
County = 0.025
Purchase = float(input(‘amount of purchase: ‘))
State_tax = purchase * state
County_tax = purchase * county
Total_tax = state_tax + county_tax
Total = purchase + total_tax
Print(‘amount: ‘ + ‘{:.2f}’.format(purchase))
Print(‘state tax: ‘ + ‘{:.2f}.format(state_tax))
Print(‘county tax: ‘ + ‘{:.2f}.format(county_tax))
Print(‘total tax: ‘ + ‘{:.2f}.format(total_tax))
Print(‘total sale: ‘ + ‘{:.2f}.format(total))
To test it I inputted 11. However, the total doesn’t add up correctly to the tax. The total tax is 0.83 but the total is 11.82. It doesn’t round 11.825 to 11.83. How could I fix this?
Because you are calculating tax total without formatting
Try this one for tax as you shown in print
total_tax = float('{:.2f}'.format(state_tax)) + float('{:.2f}'.format(county_tax))
This fix fix your total
Python usually round to min value if fraction value is less than or equal to 5, It rounds up to max value when the fraction value is above 5.
You can even try this to round the number
print("amount: {}".format(round(purchase, 2)))
To round the amount to 2 digits

Modification of Future Value

For this you have to add the annual contribution to the beginning of the year (the principal total) before computing interest for that year.
I am stuck and need help. This is what I have so far:
def main():
print("Future Value Program - Version 2")
print()
principal = eval(input("Enter Initial Principal:"))
contribution = eval(input("Enter Annual Contribution:"))
apr = eval(input("Enter Annual Percentage Rate (decimal):"))
yrs = eval(input("Enter Number of Years:"))
for k in range (1, yrs):
principal= principal * (1 + apr)
print()
print( yrs,) ": Amount $", int(principal * 100 + 0.5)/100)
main()
It is supposed to look like this:
Future Value Program - Version 2
Enter Initial Principal: 1000.00
Enter Annual Contribution: 100.00
Enter Annual Percentage Rate (decimal): 0.034
Enter Number of Years: 5
Year 1: Amount $ 1137.4
Year 2: Amount $ 1279.47
Year 3: Amount $ 1426.37
Year 4: Amount $ 1578.27
Year 5: Amount $ 1735.33
The value in 5 years is $ 1735.33
Here's a working example that produces the expected output:
def main():
print("Future Value Program - Version 2")
print()
principal = float(input("Enter Initial Principal: "))
contribution = float(input("Enter Annual Contribution: "))
apr = float(input("Enter Annual Percentage Rate (decimal): "))
yrs = int(input("Enter Number of Years: "))
print()
for yr in range(1, yrs + 1):
principal += contribution
principal = int(((principal * (1 + apr)) * 100) + 0.5) / 100
print("Year {0}: Amount $ {1}".format(yr, principal))
print()
print("The value in {0} years is $ {1}".format(yrs, principal))
if __name__ == '__main__':
main()
There were a few problems with the example in the question:
A syntax error in the print statement on line 12. Calling print with parens means all the arguments should be enclosed inside the parens. Python interpreted the errant paren as the end of arguments passed to print.
As noted by others, you shouldn't call eval on the inputs. Call float for floating point numbers, int for integers.
The range operator had an off by one error.
As noted by others, print is called outside of the loop, so intermediate states of the principal aren't output.
As far as basic maths, it seems as though adding the contribution was left out.
As per the expected output, the final print was missing.

Categories