How would I go about generating a random float and then rounding that float to the nearest decimal point in Python 3.4?
How would I go about generating a random float and then rounding that float to the nearest decimal point in Python 3.4?
Method 1:
You need two things: The random module and the builtin function round()
.
First you need a random number. This is as easy as:
import random
a = random.random()
This will produce a number between 0 and 1. Next use round()
to round it:
b = round(a, 1) # Thanks to https://stackoverflow.com/users/364696/shadowranger for the suggestion
print(b)
The second argument in round()
specifies the number of decimal places it rounds to in this case 1 which means it rounds to 1 decimal place.
and your done.
Method 2:
The other way you can do this is to use random.randint()
this will produce a whole number within a range that we can then divide by 10 to get it to one decimal place:
import random # get the random module
a = random.randint(1, 9) # Use the randint() function as described in the link above
b = a / 10 # Divide by 10 so it is to 1 decimal place.
print(b)
and your done