Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you round a string in Python?

Tags:

python

I am new to Python and a student, my college has chosen the worst book on earth for our course. I cannot find examples of any concepts, so I apologize in advance as I know these concepts are very basic. I hope you can help me.

I need to know how to use the round feature in a string. I find examples but they do not show the string, just simple numbers.

Here is what we are supposed to get as an output: Enter the gross income: 12345.67 Enter the number of dependents: 1

The income tax is $-130.87 <---- this is what we are supposed to figure out

Here is the coding we are given to alter:

TAX_RATE = 0.20
STANDARD_DEDUCTION = 10000.0
DEPENDENT_DEDUCTION = 3000.0

# Request the inputs
grossIncome = float(input("Enter the gross income: "))
numDependents = int(input("Enter the number of dependents: "))   

# Compute the income tax
taxableIncome = grossIncome - STANDARD_DEDUCTION - \
                DEPENDENT_DEDUCTION * numDependents
incomeTax = taxableIncome * TAX_RATE 

# Display the income tax

print("The income tax is $" + str(incomeTax))

As I do not have an NUMBER to plug into the formula - I have to figure out how to use "incomeTax" - I have no idea how to do this. THe book doesnt explain it. Help?

like image 648
queenv Avatar asked Jan 27 '19 02:01

queenv


People also ask

Does round () round up Python?

Python has three ways to turn a floating-point value into a whole (integer) number: The built-in round() function rounds values up and down. The math. floorfloorIn mathematics and computer science, the floor function is the function that takes as input a real number x, and gives as output the greatest integer less than or equal to x, denoted floor(x) or ⌊x⌋.https://en.wikipedia.org › wiki › Floor_and_ceiling_functionsFloor and ceiling functions - Wikipedia() function rounds down to the next full integer.

Does Python round 0.5 up or down?

In Python, the round() function rounds up or down? The round() function can round the values up and down both depending on the situation. For <0.5, it rounds down, and for >0.5, it rounds up. For =0.5, the round() function rounds the number off to the nearest even number.


2 Answers

You can use format strings:

print("The income tax is ${:.2f}".format(incomeTax))

If you are using Python 3.6+, you can also use f-strings:

print(f"The income tax is ${incomeTax:.2f}")
like image 188
iz_ Avatar answered Oct 12 '22 22:10

iz_


You can round just before making it a string:

print("The income tax is $" + str(round(incomeTax,2)))

Output:

Enter the gross income: 12345.67
Enter the number of dependents: 1
The income tax is $-130.87
like image 30
U12-Forward Avatar answered Oct 12 '22 22:10

U12-Forward