When I enter this code the answer ends with 2 characters behind the decimal. How do I make this only have 1 number behind it?
tempature=float(input("Enter the temp(F):"))
formant_tempature = f"{tempature:2f}"
print(round(((int(tempature)-32)*5/9)+273.15,2))
When you used round function you have specified that you want two decimal places. Just replace 2 with a number 1.
print(round(((int(tempature)-32)*5/9)+273.15,1))
You are using the string formatting operator for that ( formant_tempature = f"{tempature:2f}" )
What about formant_tempature = f"{tempature:1f}"
Like if you want it to display 5 decimals, just change it to f"{tempature:5f}"
And so on.
And for the round method, change 2 to 1.
I'm not sure why you'd do any math just to present this rounded, when you can simply use an f-string to specify outputting the temperature with a single decimal place precision.
>>> temperature = 43.8934
>>> print(f"Temperature is {temperature:.1f} degrees")
Temperature is 43.9 degrees
>>> print(f"Temperature is {temperature * 1.8 + 32:.1f} degrees farenheit")
Temperature is 111.0 degrees farenheit
Related
I tried creating a temperature converter below:
from decimal import *
getcontext().prec = 10
celsius = Decimal(12)
fahrenheit = celsius*9/5+32
kelvin = celsius+Decimal(273.15)
romer = celsius*21/40+Decimal(7.5)
When converted to a string, fahrenheit returns 53.6 and romer returns 13.8, both with no additional decimal places. However, kelvin returns 285.1500000. (This isn't even 285.1500001). How do I make sure it returns just enough places, i.e. 285.15? I assume it is not a problem with adding floating decimals because romer is fine.
Do simple
from decimal import *
getcontext().prec = 10
celsius = Decimal(12)
fahrenheit = celsius*9/5+32
kelvin = round(celsius+Decimal(273.15), 2) #if you need more then 2 digit replace 2 with other number
romer = celsius*21/40+Decimal(7.5)
To make it simple, you can use the built in round() function. It takes in two params, the number required to be rounded and the number of decimals to be rounded.
kelvin = round(celsius+Decimal(273.15), 2)
Here 285.1500000 will be rounded to 2 decimal place 285.15. Other method like str.format(), trunc(), round_up(), etc are also available.
You might be able to use str.format(). For example:
formatted_kelvin = "{:.2f}". format(kelvin)
So, if you printed this, it would print only 2 decimal places.
I would need to format a python Decimal object to have atleast two decimals, but no more than 5. Is there a reliable way to do this?
Examples:
1.6 --> 1.60
1.678 --> 1.678
1.98765 --> 1.98765
If there are more than two decimals, it is vital that it does not get truncated to only two decimals.
It looks to me like there are two parts to this question - one, determining the correct number of digits and two, quantizing the values to that number of digits.
To do the first, I would get the current exponent using the as_tuple() method. Unless I'm overlooking something simpler.
>>> import decimal
>>> d = decimal.Decimal("1.678")
>>> d.as_tuple().exponent
-3
>>> d2 = decimal.Decimal("1.6")
>>> d2.as_tuple().exponent
-1
So from that you can compute the desired exponent:
MAX_EXPONENT = -2
MIN_EXPONENT = -5
def desired_exponent(d):
current_exponent = d.as_tuple().exponent
return min(MAX_EXPONENT, max(MIN_EXPONENT, current_exponent))
The second is answered by the accepted answer on the marked duplicate - use the quantize() method. You'll need to construct a Decimal value with the desired exponent you can provide as the argument to quantize(). There are multiple ways to do that, but two simple ones are exponentiating decimal.Decimal("10") or using the tuple constructor for decimal.Decimal().
>>> quant_arg = decimal.Decimal("10") ** -2
>>> decimal.Decimal("1.6").quantize(quant_arg)
Decimal('1.60')
Or:
>>> quant_arg = decimal.Decimal((0, (), -2))
>>> decimal.Decimal("1.6").quantize(quant_arg)
Decimal('1.60')
I used -2 as a literal there, you'd want to use the calculated value of desired_exponent.
There are multiple ways to organize this code, I think the parts that are not obvious are a) accessing the current exponent of a decimal value and b) some of the ways of constructing an arg for quantize(). And this is all assuming you need the actual decimal objects, and aren't just outputting them - if this is a question just about output formatting re-quantizing is probably overkill.
Here is the code I use now:
def unitAmount(value):
"""Format a Decimal to match -?[0-9]{1,15}(,[0-9]{2,5})?
Minimum two decimals, max 5.
"""
decimals = value.as_tuple().exponent
if decimals == -1: # For values like 1.6 --> 1.60
value = value.quantize(Decimal('1.00'))
elif decimals < -5: # For values like 1.1234567.. --> 1.12345
value = value.quantize(Decimal('1.00000'))
return value
I have a float that has 16 decimal places, but I want it to be capped at 6, and if I ever get a float that has less than 6 decimals, I want it to add 0s until it has 6.
i.e.:
1.95384240549 = 1.953842
3.12 = 3.120000
I'm trying to generate a value based on a certain amount of demand an object has. Thanks!
To round to a certain amount of decimals you can use round()
Example:
round(1.95384240549,6) > 1.953842
And for more 0's after the decimal place you can use format():
format(3.12, '.6f') > '3.120000'
Note this is of type string
Read more here:
Rounding syntax
Format syntax
A bit more complex than the previous answer, but more consistent.
import math
def truncate(number, digits) -> float:
places = len(str(number)[str(number).find("."):])
if places > 6:
stepper = 10.0 ** digits
return math.trunc(stepper * number) / stepper
else:
return str(number) + "0"*(6 - places)
Examples: truncate(3.12 , 6) returns 3.120000 and truncate(1.95384240549, 6) returns 1.953842
I am trying to create a Python function that calculates the average of 3 temperatures. I am a beginner at Python so I wanted to make sure I am on the right track.
This is what I have so far:
def average(temp_one, temp_two, temp_three):
avg = (int(temp_one) + int(temp_two) + int(temp_three))/3
return avg
Then I have to use the function created that prompts for 3 temperatures and calculates the average. The average output must include one decimal place.
def average(temp_one, temp_two, temp_three):
avg = (int(temp_one) + int(temp_two) + int(temp_three))/3
return (avg)
temp_one = float(input(“Enter temperature one:”))
temp_two = float(input(“Enter temperature two:”))
temp_three = float(input(“Enter temperature three:”))
average = ( temp_one+ temp_two + temp_three ) // 3
print (average(temp_one, temp_two, temp_three))
For this part I am not very sure of.. Any help is appreciated, thank you!
1. Your calculation is doing unnecessary casts to int which loses some precision. In fact, it truncates decimal places, thus lowers your average artificially.
2. You are not using the function you have written. Instead you repeat your calculation code with integer division //. Note that:
5 / 2 == 2.5 # floating point division
5 // 2 == 2 # integer division
so here, you are losing information as well.
3. You should format your output to one decimal place. This is best done using string formatting
Thus:
def average(temp_one, temp_two, temp_three):
return (temp_one + temp_two + temp_three) / 3
# why cast to int and lose precision
# read your 3 float inputs ...
avg = average(temp_one, temp_two, temp_three) # actually use your function
print('{:.1f}'.format(avg)) # format output
"%0.1f"%my_float
#or
"{0:0.1f}".format(my_float)
#or
"{my_float:0.1f}".format(my_float=my_float)
will print a float with 1 decimal place see also python format strings
I am trying to write a function to round a floating point number up to n decimal places. The function can take one or two arguments. If there is only one argument the number should be rounded to two decimal places.
This is where I have gotten so far:
def roundno(num,point=2):
import math
x=1*(math.pow(10,-point))
round=0
while (num>x):
while(num>0):
round+=num/10
num=num/10
round*=10
round+=num/10
num=num/10
round*=0.1
return round
I am getting infinity as the output, every time... Where did I go wrong?
I can't see how your algorithm is supposed to round numbers. I guess a similar strategy could work, but you'd need a subtraction in there somewhere...
One way to do this would be to convert the argument to a string, adjust the number of digits after the decimal point, and then convert the string back to a float, but I suspect that your teacher would not like that solution. :)
Here's a simple way to do rounding arithmetically:
def roundno(num, point=2):
scale = 10.0 ** point
return int(num * scale) / scale
data = [123, 12.34, 1.234, 9.8765, 98.76543]
for n in data:
print n, roundno(n), roundno(n, 3)
output
123 123.0 123.0
12.34 12.34 12.34
1.234 1.23 1.234
9.8765 9.87 9.876
98.76543 98.76 98.765
This simply drops unwanted digits, but it's not hard to modify it to round up or off (your question isn't clear on exactly what type of rounding you want).
Note that this function doesn't check the point argument. It really should check that it's a non-negative integer and raise ValueError with an appropriate error message otherwise.