Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print either an integer or a float with n decimals

In Python, how can one print a number that might be an integer or real type, when the latter case would require me to limit my printout to a certain amount of digits?

Long story short, say we have the following example:

print("{0:.3f}".format(num)) # I cannot do print("{}".format(num))
                             # because I don't want all the decimals

Is there a "Pythy" way to ensure e.g. in case num == 1 that I print 1 instead of 1.000 (I mean other than cluttering my code with if statements)

like image 289
Lorah Attkins Avatar asked Feb 27 '17 15:02

Lorah Attkins


People also ask

How do you print a float with 2 decimals in Python?

Use the round() function to print a float to 2 decimal places, e.g. print(round(my_float, 2)) . The round() function will round the floating-point number to 2 decimal places and will return the result.


1 Answers

If you need to maintain a fixed-width for float values, you could use the printf-style formatting, like this:

>>> num = 1
>>> print('%0.*f' % (isinstance(num, float) * 3, num))
1
>>> num = 1.2345
>>> print('%0.*f' % (isinstance(num, float) * 3, num))
1.234
>>> num = 1.2
>>> print('%0.*f' % (isinstance(num, float) * 3, num))
1.200
like image 103
ekhumoro Avatar answered Oct 23 '22 14:10

ekhumoro