简体   繁体   中英

Python and Floats - Print only the Whole Number

Is there a way in Python to print only the whole number portion of a float when no additional precision is required to express the number? For example, the float 1.0. Some other languages do this by default. Here are some examples:

In C++, this code prints 1, not 1.0:

int main()
{ 
    float f = 1.0;
    std::cout << f << "\n";

    return 0;
}

./a.out 
1

However, in Python, this code prints 1.0:

f = 1.0

print type(f)
<type 'float'>

print f
1.0

I'd like for the Python code to only print 1, not 1.0, when that's all that is required to fully represent the number.

Use the g formatting option:

f = 1.0
print(f"{f:g}")           # Python 3.6 and above

or

print "{:g}".format(f)

or

print "%g" % f

This does something very similar to std::cout in default configuration. It will only print a limited number of digits, just like std::cout .

The modulo operator should work across all Python versions:

>>> f = 1.0
>>> if f % 1 == 0:
...     print int(f)
... else:
...     print f
... 
1
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM