-1

For example, I'm trying to have the following return as 5.90

test = round(5.9, 2)
print(test)
  • So after rounding up, you want your answer to have 2 decimal places? – Swetank Poddar May 18 '20 at 22:16
  • What a float is and how you choose to format it when printing are two different questions which you are conflating. – John Coleman May 18 '20 at 22:16
  • Does this answer your question? [Python, print all floats to 2 decimal places in output](https://stackoverflow.com/questions/2075128/python-print-all-floats-to-2-decimal-places-in-output) – John Coleman May 18 '20 at 22:17
  • @JohnColeman Really bad leagacy Python 2 question dupe target. There probably exists a million good ones though. – ruohola May 18 '20 at 22:21
  • @ruohola perhaps you could add a more recent answer to that question. I would happily upvote it. The answers to these questions tend to evolve over time, with newer answers often added. – John Coleman May 18 '20 at 22:24
  • @JohnColeman I'd rather not, since that question is explicitly asking about Python 2. – ruohola May 18 '20 at 22:25
  • Does this answer your question? [print float to n decimal places including trailing 0's](https://stackoverflow.com/questions/8568233/print-float-to-n-decimal-places-including-trailing-0s) – ruohola May 18 '20 at 22:31

3 Answers3

1

You can't control how many decimals floats have when you print them as is. To have control over that, you need to format the float into a string and then print that.

For example:
(Also: No point in rounding a number with 1 decimal point to the precision of 2 decimal points.)

test = 5.9 
print(f"{test:.2f}")

Output:

5.90

You can read more about string formatting here: https://docs.python.org/3/library/string.html#format-specification-mini-language

ruohola
  • 21,987
  • 6
  • 62
  • 97
0

You can use %.2f instead.. for example:

    test = round(5.9, 2)
    print("%.2f"%test)

it will output 5.90.u can replace 2 with how many u wan to have numbers after decimal point

anas
  • 162
  • 1
  • 10
-1

this works for python2 and python3

n = 5.9
print('%.2f' % n)  # -> 5.90

in python3 also works

print('{:.2f}'.format(n))  # -> 5.90

and since python 3.7 also works:

print(f'{n:.2f}')  # -> 5.90
angeldeluz777
  • 319
  • 3
  • 4