Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

python - 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

So we've got 4 numbers (who are not in a list anymore). Two numbers with a decimal and two whole numbers.

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).

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?

Edit: the relevant code, as asked:

# 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

EDIT

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. 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...