Home python Python: How to withdraw the number of type Float with a certain...

Python: How to withdraw the number of type Float with a certain number of semicolons

Author

Date

Category

There is this feature:

Def Vol (RAD):
  Print (4/3 * 3.141592 * RAD ** 3, "CM ^ 3")

output will be:

vol (5)
523.5986666666666 CM ^ 3

Question: how to display a response with a certain number of semicolons, chapel 523.598 or 523.59 as possible while retaining the code compactness


Answer 1, Authority 100%

For example, using a string method Format :

& gt; & gt; & gt; "{0: .2f}." Format (70.12312312)
'70 .12 '

There are many options, to format output, you can read more in Documentation .

In your case, you need to display in print not numbers, but a string with formatting, for example:

& gt; & gt; & gt; DEF Vol (RAD):
.... Print ("{0: .2f} cm ^ 3" .Format (4/3 * 3.141592 * RAD ** 3))
& gt; & gt; & gt; Vol (5)
523.60 cm ^ 3

More interesting formatting methods are on ENSO . There a little different output wanted to receive the author, but it is possible to peering the way.


Answer 2, Authority 100%

This option will arrange?

RAD = 5
Print (4/3 * 3.141592 * RAD ** 3, "CM ^ 3")
# 523.5986666666666 cm ^ 3
Print ("{0: .4f} cm ^ 3" .Format (4/3 * 3.141592 * RAD ** 3))
# 523.5987 cm ^ 3

either through F-Strings, which will be quickly:

res = 4/3 * 3.141592 * RAD ** 3
Print (F '{res: .4f} cm ^ 3')
# 523.5987 cm ^ 3

Answer 3, Authority 50%

Def Vol (RAD, F):
  Print ("{:. {} f} {}". Format (4/3 * 3.141592 * RAD ** 3, F, "CM ^ 3"))
Vol (5, 3)
523.599 cm ^ 3
Vol (5, 2)
523.60 cm ^ 3

Answer 4, Authority 50%

There is a special function Round

x = 4.4444
Print (Round (x, 2)) # 4.44

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions