How would I go about generating a random float and then rounding that float to the nearest decimal point in Python 3.4?
Asked
Active
Viewed 4,368 times
-3
-
random float between which and which values? – Basj Jan 05 '18 at 23:17
-
2you can find the documentation under [random](https://docs.python.org/3.4/library/random.html) , [round](https://docs.python.org/3.4/library/stdtypes.html) – Amos Egel Jan 05 '18 at 23:19
-
1why can't you generate a random integer instead? – Moinuddin Quadri Jan 06 '18 at 00:44
-
4Possible duplicate of [How to get a random number between a float range?](https://stackoverflow.com/questions/6088077/how-to-get-a-random-number-between-a-float-range) – Moinuddin Quadri Jan 06 '18 at 00:45
-
1@MoinuddinQuadri Thanks for the retag. Good idea. I'll just include that in my answer. If you don't object. – Xantium Jan 06 '18 at 00:46
-
@Simon Sure. Go ahead. – Moinuddin Quadri Jan 06 '18 at 00:48
2 Answers
2
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

Xantium
- 11,201
- 10
- 62
- 89
-
2You don't need to multiply or divide at all. `round` takes two arguments, where the second is the number of digits to round to, so you could just do `b = round(a, 1)`, which directly rounds to a single digit after the decimal in a single step. – ShadowRanger Jan 06 '18 at 00:53
-
1
Assuming you want a float between 0.0 and 1.0, you can do it with:
import random
print(int(random.random()*10) / 10.0)
(Note that the division is by 10.0 and not 10 to force the float operation)
Output:
0.2
0.6
0.8
...

Basj
- 41,386
- 99
- 383
- 673
-
2
-
1
-
3Notes: 1. The OP specified Python 3; `/ 10` will work just fine (because `/` is true division on Py3, not floor division). 2. This doesn't round to *nearest* decimal, it rounds towards zero (if you generated `0.99999`, `9.9999` would be truncated to `9`, then division would get you `0.9`, not the closer `1.0`). – ShadowRanger Jan 06 '18 at 00:50