仅当小数点不是整数时如何显示小数点? [英] How to show decimal point only when it's not a whole number?
问题描述
我用谷歌搜索过,但找不到正确的答案.
I have Googled, but couldn't find a proper answer to this.
假设我们有浮点数并且我们得到了它们的平均值.他们的平均值是这样的:
Let's say we have floats and we get their averages. Their averages are like this:
3.5
2.5
5
7
所以我们有 4 个号码(不再在列表中).两个带小数和两个整数的数字.
So we've got 4 numbers (who are not in a list anymore). Two numbers with a decimal and two whole numbers.
我想做的是,打印这些数字并保持这样.不过,我的问题是,当我使用 %.1f
时,它会从 5 和 7 生成 5.0 和 7.0,而我想保持它们原样 (因此将它们作为一个整体保留号).
What I want to do is, to print these numbers and keep them like this. My problem is, though, that when I use %.1f
, it makes 5.0 and 7.0 from 5 and 7, while I want to keep them as they are (so keep them as a whole number).
所以我想按原样打印它们,但我不知道如何打印.Float 将 decimal
点添加到整数.将它们转换为 int
,删除所需的小数.
So I'd like to print them exactly as they are, but I don't know how. Float adds decimal
points to whole numbers. Converting them to an int
, removes the needed decimals.
这两个选项都不是我想要的.
Both options are not what I want.
有人能指出我正确的方向吗?
Can someone point me in the right direction?
相关代码,如问:
# I have a list of numbers and I am calculating their average and rounding them first.
get_numbers = map(float, line[-1])
average_numbers = sum(get_numbers) / len(get_numbers)
rounded_numbers= round(average_numbers * 2) / 2
# So now, I've got the numbers: 3.5, 2.5, 5, 7
print "The numbers are: %.1f" % (rounded_numbers)
推荐答案
您可以使用浮动的 is_integer 方法.如果浮点数可以表示为整数(换句话说,如果它的形式为 X.0
),则返回 True
:
You can use floats' is_integer method. It returns True
if a float can be represented as an integer (in other words, if it is of the form X.0
):
li = [3.5, 2.5, 5.0, 7.0]
print([int(num) if float(num).is_integer() else num for num in li])
>> [3.5, 2.5, 5, 7]
编辑
在 OP 添加他们的代码之后:
After OP added their code:
不要像在上面的原始示例中那样使用列表推导式,您应该对计算的平均值使用相同的逻辑:
Instead of using list comprehension like in my original example above, you should use the same logic with your calculated average:
get_numbers = map(float, line[-1]) # assuming line[-1] is a list of numbers
average_numbers = sum(get_numbers) / len(get_numbers)
average = round(average_numbers * 2) / 2
average = int(average) if float(average).is_integer() else average
print average # this for example will print 3 if the average is 3.0 or
# the actual float representation.
这篇关于仅当小数点不是整数时如何显示小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!