How to keep my numbers from rounding? [duplicate] - python

This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 9 years ago.
I have some code that takes values from a dictionary and attempts to figure out the per unit price of an item. However, I cannot figure out how to keep the values from rounding.
If I do this:
total_price = int(item['Item Price'][1:]) #First character is a dollar sign
qty = int(item['Quantity'])
unit_price = total_price/qty
I get this error:
ValueError: invalid literal for int() with base 10: '88.75'
So, I tried floating the value:
total_price = int(float(item['Item Price'][1:]))
qty = int(item['Quantity'])
unit_price = total_price/qty
Which doesn't return an error, but it then rounds up and I only get whole numbers.
How can I get the actual per piece price and not a rounded value? Thanks

Change your qty and total_price to be a float:
total_price = float(item['Item Price'][1:])
qty = float(item['Quantity'])
This will cause the division to be between two floating point values.
Using int explicitly says you want integers, which gives you whole numbers.

The error is occurring during division
>>> print 3/2
1
>>> print 3.0/2
1.5
>>>

Related

Program printing a number a certain times instead of multiplying [duplicate]

This question already has answers here:
Why does multiplication repeats the number several times? [closed]
(7 answers)
Closed 1 year ago.
I’ve written a piece of code that instead of print the product, prints a number a certain number of times. Whats wrong with it?
twelve = 12
name = input("What is your name? \nAnswer: ")
print("Cool name!")
nums = input("\n\nHow much pocket money did you receive last month?\nAnswer: ")
total = nums * twelve
print("\n\nI think you get ", total + " pounds in pocket money per year! Nice!")
The reason is that your nums variable is a string, which is the default with all Python inputs. Try converting it to int:
nums = int(input(...))
Or float if you are inputting a floating point number.

how to print a float to 2 decimal places [duplicate]

This question already has answers here:
How to display a float with two decimal places?
(13 answers)
Closed 3 years ago.
I want number from input to print out with 2 decimal places. You can assume that the number will always be a float.
num = 20.0
Desired output - 20.00.
I've tried this code:
num = round(num, 2)
num = float('{0.2f}'.format(num))
print(num)
This should work
print('{0.2f}'.format(num))
When you turn this string back into a float with float() the formatting is lost.
No matter what you do to the float value, as long as it is still a float, it does not have any internal concept of decimal places.
If you want to display two decimal places, then that happens when you convert to text - which everything you print is, whether you asked for the conversion or not. You cannot make num "be" 20.00 as opposed to 20.0, because those aren't actually different things. (And keep in mind that the float simply cannot represent all decimal values exactly.)
Therefore, we use string formatting in the print call:
num = 20.0
print('{.2f}'.format(num))
# Or, using f-strings:
print(f'{num:.2f}')

Having trouble converting result produced into a float with python [duplicate]

This question already has answers here:
I need to convert the interest rate to a decimal value
(1 answer)
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 6 years ago.
I am trying to get a float value but it keeps on giving me a decimal value as an answer.
import math
p = int(raw_input("Please enter deposit amount: \n"))
r = int(raw_input("Please input interest rate: \n"))
t = int(raw_input("Please insert number of years of the investment: \n"))
interest = raw_input("Do you want a simple or compound interest ? \n")
A = p*(1+r*t)
B = p*(1+r)^t
if interest == "simple":
print (float(A/100))
else:
print(float(B/100))
float(A/100) first calculates A/100, which are both ints, so the result is an int, and only then converts to float. Instead you could use:
float(A)/100
or:
A/100.
Here is the problem. In python2 the division between integers gives another integer (this is not true in python3).
42 / 100 # return 0
The solution is to keep one to float.
42 / 100.0 #return 0.42

Convert a floating point number to an integer except math.floor() [duplicate]

This question already has answers here:
Round a floating-point number down to the nearest integer?
(12 answers)
Closed 7 years ago.
Is there any way to convert a floating point number in Python to an integer except math.floor()?
I have already tried math.floor(), but I am getting an error says:
Cannot import math
Any other way?
Use the int() function
print int(5.3) # "5"
For more info
You can:
Use int(3.14)
import math then math.floor(3.14) or math.ceil(3.14) (depending on which way you want to round) (you said this doesn't work but I'll leave it for reference)
x = x - x % 1 or x -= x % 1

Python, Averages, and Division [duplicate]

This question already has answers here:
Python rounding error with float numbers [duplicate]
(2 answers)
Python floating-point math is wrong [duplicate]
(2 answers)
Closed 9 years ago.
first = float(input("Enter first number: "));
second = float(input("Enter second number: "));
avg = float((first + second) / 2);
print(str(avg));
Using the numbers 1.1 and 1.3 as inputs, the expected output is 1.2. However, the result I'm receiving is 1.2000000000000002. I understand that this is related to Python and it's datatypes.
However, I'm unsure of how to evaluate this correctly, or why this specific result is achieved.
EDIT: Python 3.2
Use decimals:
import decimal
first = decimal.Decimal('1.1')
second = decimal.Decimal('1.3')
avg = (first + second) / 2
print(avg)

Categories