-2

I was doing an exercise of my python class and after seeing the results i was imagining what could i do to shorten the resultant variable (to avoid results like: 3.888888888, and transform it to 3.8 or 3.88. Someone could help me?! (Also the code is working very well i just wanna improve it)

OBS: My code is at my native language, so ill explain. The user type a number and it will show your double, triple, square root (b,c and d; respectively)

a = float(input("Digite um número para descobrir: \n\nSeu Dobro \nSeu Triplo \nSua Raiz Quadrada \n\nDigite um número: "))
b = a * 2
c = a * 3
import math
d = math.sqrt(a)
print()
print("RESULTADOS: \n\nDobro: {} \nTriplo: {} \nRaiz Quadrada: {} \n".format(b, c, d))
Random Davis
  • 6,662
  • 4
  • 14
  • 24
  • Sounds like you should use [round](https://docs.python.org/3/library/functions.html#round). – Random Davis Mar 26 '21 at 22:55
  • you can do something like `print("RESULTADOS: \n\nDobro: {} \nTriplo: {} \nRaiz Quadrada: {}%.2f \n".format(b, c, d))` – Bijay Regmi Mar 26 '21 at 22:58
  • 1
    Does this answer your question? [Limiting floats to two decimal points](https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) – PApostol Mar 26 '21 at 22:58
  • Possible duplicate [here](https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points), and more examples [here](https://www.kite.com/python/answers/how-to-print-a-float-with-two-decimal-places-in-python) and [here](https://www.kite.com/python/answers/how-to-print-a-float-with-two-decimal-places-in-python). The term you are looking for is `formatting` or `rounding`. – Thymen Mar 26 '21 at 23:00
  • @RandomDavis Well, actually this worked, but i also have seen a way that in the "{}" spaces i could write like {:.2} or {:.3} to shorten it, what is more quickly, but i dont remember very well – Pedro Tigre Mar 26 '21 at 23:07
  • IMX, `round` is basically never the right answer, because of [the usual floating-point stuff](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). People only care about "digits" in floating-point numbers because they are *displaying* a value; therefore, the appropriate tools are the string formatting tools. – Karl Knechtel Mar 26 '21 at 23:30

1 Answers1

2

You could try using the round() function

round(number, digits_after_decimal) example below:

print(round(3.88888, 2))
print(round(3.33333, 3))

3.89
3.333

Hope this is helpful

Ucef
  • 63
  • 1
  • 1
  • 5
  • Thank you guys for thw answers, actually the option that was more quickly and easy was using inside the keys {} like {:.2f} or {:.3f} – Pedro Tigre Mar 26 '21 at 23:12