Python and Floats – Print only the Whole Number
Question:
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.
Answers:
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
>>>
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
>>>