Answer a question

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)

Answers

With Python 3*, you can just use round() because in addition to rounding floats, when applied to an integer it will always return an int:

>>> num = 1.2345
>>> round(num,3)
1.234
>>> num = 1
>>> round(num,3)
1

This behavior is documented in help(float.__round__):

Help on method_descriptor:

__round__(...)
    Return the Integral closest to x, rounding half toward even.
    When an argument is passed, work like built-in round(x, ndigits).

And help(int.__round__):

Help on method_descriptor:

__round__(...)
    Rounding an Integral returns itself.
    Rounding with an ndigits argument also returns an integer.

* With Python 2, round() always returns a float.

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐