Limit decimal places

Asked

Viewed 115 times

0

I’m making a simple program that generates two random numbers and asks the user how much is that number +,-,/,* for another number, and I want them to have decimal numbers as well, but when I use the uniform() It generates a lot of decimals, and I don’t want that, I want to limit it to three houses. But I need to do this right in the definition of variables, and this I don’t know how, does anyone know?

Code:

n1 = str(uniform(1,1000))
# gera um número float de 1 à 999.
    
n2 = str(uniform(1, 1000))
# gera um número float de 1 à 999.

(I’m using str to use in the future on an Eval)

2 answers

3

Do it like this, put the expression uniform(1, 1000) within the round function. Where parameter n is the number of decimal places you want. will stay like this:

n1 = str(round(uniform(1, 1000), n))
n2 = str(round(uniform(1, 1000), n))
  • n1 = str(round(uniform(1, 1000), 3))
print(n1) sometimes it works, sometimes it doesn’t. I’d prefer something like :.3f

1

You can round the value to a certain precision of decimal digits with round() and format the output as a fixed point decimal with the number of decimal places desired:

from random import uniform

def truncar(valor, casas):
    return f"{round(valor, casas):.{casas}f}"

print(truncar(uniform(1, 1000), 3))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.