How to show decimal point only when it's not a whole number?

后端 未结 3 1053
半阙折子戏
半阙折子戏 2020-12-03 15:14

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.         


        
相关标签:
3条回答
  • 2020-12-03 15:40

    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. 
    
    0 讨论(0)
  • 2020-12-03 15:42

    Similar to the previous answer:

    [int(i) if int(i) == i else i for i in li]
    

    Or:

    [int(i) if not i % 1 else i for i in li]
    
    0 讨论(0)
  • 2020-12-03 16:04

    Technically, if you have floats and get their averages, you SHOULD get floats back. But if you just want to print them, the following should work well:

    print('{} {} {} {}'.format(3.5, 2.5, 5, 7))
    
    0 讨论(0)
提交回复
热议问题