I want to generate a floating point random number with two precision.
For example:2.54
How to change the uniform(a,b)
in python.
Thanks
Asked
Active
Viewed 2.6k times
10

user3356423
- 171
- 1
- 1
- 10
-
3You are confusing `fixed point` with `floating point` you can't generate floating point numbers with a precision of 2 decimal places. (though you can print them to 2 decimal places). If you require 2 decimals places look at the `Decimal` type in the `decimal` module. – AChampion May 25 '17 at 04:45
-
1You can do it in a hacky way generating 3 digit random number and dividing it by 100 – Arun G May 25 '17 at 04:47
-
I'm not totally sure if you want two decimals, or randmon between two values? maybe you can clarify a little – developer_hatch May 25 '17 at 05:05
-
@ArunG, how would be that? Could I see if you don't mind, I didn't follow you sorry – developer_hatch May 25 '17 at 05:06
3 Answers
15
You can use round function with uniform function to limit float number to two decimal places.
Example:
round(random.uniform(1.5, 1.9),2)
Out[]: 1.62
round(random.uniform(1.5, 1.9),3)
Out[]: 1.885

Sayali Sonawane
- 12,289
- 5
- 46
- 47
-
Thank you! And what should I do If I want to generate it fixed whenever I run my program? – user3356423 May 25 '17 at 05:12
-
if you want fixed number then just apply round(any_number,2). random.uniform will generate different value every time. – Sayali Sonawane May 25 '17 at 05:37
4
This could be the possible solution, As requested by @Damian
>>> from random import randint
>>> randint(100, 999)/100.00
7.32
>>> randint(100, 999)/100.00
4.69
>>> randint(100, 999)/100.00
5.36

Arun G
- 1,678
- 15
- 17
2
If you want to generate a random number between two numbers, with a specific amount of decimals, here is a way:
import random
greaterThan = float(1)
lessThan = float(4)
digits = int(2)
rounded_number = round(random.uniform(greaterThan, lessThan), digits)
in this case, your random number will be between 1 and 4, with two digits

developer_hatch
- 15,898
- 3
- 42
- 75