jeudi 23 juillet 2015

Python - random float with limited decimal digits

I just found out how to make random numbers in Python, but if I print them out, they all have 15 decimal digits. How do I fix that? Here is my code:

import random
import os

greaterThan = float(input("Your number will be greater than: "))
lessThan = float(input("Your number will be less than: "))
digits = int(input("Your number will that many decimal digits: "))

os.system('cls')

if digits == 15:
    print(random.uniform(greaterThan, lessThan))

if digits == 14:
    print(random.uniform(greaterThan, lessThan))

if digits == 13:
    print(random.uniform(greaterThan, lessThan))

if digits == 12:
    print(random.uniform(greaterThan, lessThan))

if digits == 11:
    print(random.uniform(greaterThan, lessThan))

if digits == 10:
    print(random.uniform(greaterThan, lessThan))

*(this just continues down to 0)

I know you can do like print("%.2" % someVariable) but the random numbers Python creates with this method are not saved in any variables. At least I think so. I would also like to know if there is a way of letting a variable choose the amount of decimal points, like print("%." + digits % anotherVariable) but I tried tha out and of course it failed.

I really got no idea. Hopefully you can help. Thanks.




Aucun commentaire:

Enregistrer un commentaire