[英]Python and Floats - Print only the Whole Number
在 Python 中,當不需要額外的精度來表達數字時,有沒有辦法只打印浮點數的整數部分? 例如,浮動 1.0。 其他一些語言默認這樣做。 這里有些例子:
在 C++ 中,此代碼打印 1,而不是 1.0:
int main()
{
float f = 1.0;
std::cout << f << "\n";
return 0;
}
./a.out
1
但是,在 Python 中,此代碼打印 1.0:
f = 1.0
print type(f)
<type 'float'>
print f
1.0
我希望 Python 代碼僅打印 1,而不是 1.0,而這正是完全表示該數字所需的全部內容。
使用g
格式化選項:
f = 1.0
print(f"{f:g}") # Python 3.6 and above
要么
print "{:g}".format(f)
要么
print "%g" % f
這與默認配置中的std::cout
非常相似。 它只會打印有限數量的數字,就像std::cout
一樣。
模運算符應該適用於所有 Python 版本:
>>> f = 1.0
>>> if f % 1 == 0:
... print int(f)
... else:
... print f
...
1
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.