Python - random float with limited decimals

I just found out how to make random numbers in Python, but if I print them out, all of them will have 15 decimal digits. How to fix it? 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 only continues to 0)

I know what you can do as print("%.2" % someVariable), but the random numbers created by Python using this method are not stored in any variables. At least I think so. I would also like to know if there is a way to let the variable select the number of decimal points, for example print("%." + digits % anotherVariable), but I tried this and of course it didn’t work.

I really had no idea. Hope you can help. Thank.

+4
source share
3 answers

, random.uniform, , round().

. :

import random

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: "))

rounded_number = round(random.uniform(greaterThan, lessThan), digits)
print(rounded_number)
+10

float .format():

print float("{0:.2f}".format(random.uniform(greaterThan, lessThan)))

2 , .

+2

, "", , , , , .

, , :

import decimal

!

Edit:

, . ? digits , ? , ( ), .

If you really do something different for each value digits, then you should use if-elif-else:

if digits == 15:
    do_stuff()
    ...
elif digits == 14:
    do_other_stuff()
    ...
elif digits == 13:
    do_even_moar_different()
    ...
...
else:
    and_now_for_something_completely_different()

But this is ugly, and Python should be pretty ( import this).

if digits > some_value:
    do_stuff()
    ...
elif digits <= some_other_value:
    do_something_else()
...

I recommend that you read floating point arithmetic , as it is very important to understand at least a little.

+1
source

Source: https://habr.com/ru/post/1599380/


All Articles