pythonrandomfloating-point

How to generate random float numbers?


I want to generate random number between 0 and 1 in python but only get 2 numbers after sign. Example:

0.22 
0.25
0.9

I have searched many sources but have not found the solution. Can you help me?


Solution

  • You can use the format method in python if you want EXACTLY 2 digits after the decimal point (for example if you want 0.90):

    import random
    
    x = random.random()
    print("{:.2f}".format(x))
    

    or if you are fine with numbers like 0.9:

    import random
    
    x = random.random()
    print(round(x,2))