在 Python 3.x 中显示两位小数...但也没有这些小数点,如果适用 - 怎么样?

Displaying to two decimal points in Python 3.x... but also without these decimals, if applicable - how?

在 Python 3.8 中,我试图获取一个浮点值来显示如下:

我知道 "round"。如果我有这个程序:

print ('input a number')
chuu = float(input())
chuu = round(chuu,2)
print (chuu)

我也知道我可以做到这一点:

print ('input a number')
chuu = float(input())
print('{0:.2f}'.format(chuu))

这也不符合我的要求:

如何解决这个问题?

你可以简单地这样做

print ('input a number')
chuu = float(input())
chuu = round(chuu,2)
if int(chuu)==chuu:
    print(int(chuu))
else:
    print(chuu)

你的意思是这样的?

def specialRound(num):
    #check if has decimals
    intForm = int(num)
    if(num==intForm):
        return intForm
    TDNumber = round(num,2) #Two decimals
    ODNumber = round(num,1) #One decimal
    if(TDNumber>ODNumber):
        return TDNumber
    return ODNumber

print(specialRound(3.1415))
print(specialRound(3.10))
print(specialRound(3))

您可以使用字符串格式化的通用格式类型。

print('input a number')
chuu = float(input())
print('{:g}'.format(round(chuu, 2)))

看看合不合适!

chuu = 4.1111             #works for 4, 4.1111, 4.1

print(chuu if str(chuu).find('.')==-1 else round(chuu,2))      

编辑:

@Mark 非常准确地指出了上述方法中的潜在缺陷。

这是一种修改后的方法,支持多种可能性,包括@mark 指出的内容。

print(chu if type(chu)!=float else ('{0:.2f}' if(len(str(chu).split('.')[-1])>=2) else '{0:.1f}').format(round(chu,2)))

满足所有这些可能性:

#Demonstration
li = [0.00005,1.100005,1.00001,0.00001,1.11111,1.111,1.01,1.1,0.0000,5,1000]
meth1 = lambda chu: chu if type(chu)!=float else ('{0:.2f}' if(len(str(chu).split('.')[-1])>=2) else '{0:.1f}').format(round(chu,2))

print(*map(meth1,li))

output
0.00 1.10 1.00 0.00 1.11 1.11 1.01 1.1 0.0 5 1000

注意:不适用于负数

此解决方案更基于字符串

def dec(s):
    s = s.rstrip('.')
    if(s.find('.') == -1): 
        return s
    else:
        i = s.find('.')
        return s[:i] + '.' + s[i+1:i+3]


print(dec('3.1415'))
print(dec('3'))
print(dec('1234.5678'))
print(dec('1234.5'))
print(dec('1234.'))
print(dec('1234'))
print(dec('.5678'))

3.14
3
1234.56
1234.5
1234
1234
.56

如果您只想要它用于打印,则可以使用以下方法。

from decimal import Decimal

print('Input a number: ')
chuu = float(input())

print(Decimal(str(round(chuu, 2))).normalize())

但是,这会将像 3.0 这样的数字变成 3。(不清楚您是否想要这种行为)