Python print out float or integer

后端 未结 4 1398
难免孤独
难免孤独 2020-12-20 00:30

How can i print out float if the result have decimal or print out integer if the result have no decimal?

c = input(\"Enter the total cost of purchase: \")
ba         


        
相关标签:
4条回答
  • 2020-12-20 01:00

    You can try this, which simply uses Python's string formatting method:

    if int(c) == float(c):
        decimals = 0
    else:
        decimals = 2 # Assumes 2 decimal places for money
    
    print('Please pay: ${0:.{1}f}'.format(c, decimals))
    

    This will give you the following output if c == 1.00:

    Please pay: $1
    

    Or this output if c == 20.56:

    Please pay: $20.56
    
    0 讨论(0)
  • 2020-12-20 01:02

    Python floats have a built-in method to determine whether they're an integer:

    x = 212.50
    y = 212.0
    f = lambda x: int(x) if x.is_integer() else x
    print(x, f(x), y, f(y), sep='\t')
    >> 212.5    212.5   212.0   212
    
    0 讨论(0)
  • 2020-12-20 01:10

    Since there is a much simpler way now and this post is the first result, people should now about it:

    print(f"{3.0:g}")  # 3
    print(f"{3.14:g}")  # 3.14
    
    0 讨论(0)
  • 2020-12-20 01:19
    def nice_print(i):
        print '%.2f' % i if i - int(i) != 0 else '%d' % i
    
    nice_print(44)
    44
    
    nice_print(44.345)
    44.34
    

    in Your code:

    def nice_number(i):
        return '%.2f' % i if i - int(i) != 0 else '%d' % i
    
    c = input("Enter the total cost of purchase: ")
    bank = raw_input("Enter the bank of your credit card (DBS, OCBC, etc.): ")
    dbs1 = ((c/float(100))*10)
    dbs2 = c-dbs1
    ocbc1 = ((c/float(100))*15)
    ocbc2 = c-ocbc1
    
    
    if (c > 200):
        if (bank == 'DBS'):
            print('Please pay $'+nice_number(dbs2))
        elif (bank == 'OCBC'):
            print('Please pay $'+nice_number(ocbc2))
        else:
            print('Please pay $'+nice_number(c))
    else:
        print('Please pay $'+nice_number(c))
    
    0 讨论(0)
提交回复
热议问题