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
gformatting option:or
or
This does something very similar to
std::coutin default configuration. It will only print a limited number of digits, just likestd::cout.