簡體   English   中英

在 Python 3.x 中顯示到兩個小數點……但也沒有這些小數點(如果適用) - 如何?

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

在 Python 3.8 中,我試圖讓一個浮點值顯示如下:

  • 如果數字的小數點超過 2 位,則應四舍五入到小數點后 2 位。
  • 如果數字有一位小數,它應該只顯示一位小數。
  • 如果數字沒有小數點,則根本不應該顯示小數點。

我知道“圓”。 如果我有這個程序:

print ('input a number')
chuu = float(input())
chuu = round(chuu,2)
print (chuu)
  • 輸入 3.141 結果為 3.14(好)
  • 輸入 3.1 結果為 3.1(好)
  • 輸入 3 結果為 3.0(不好,我想要 3)

我也知道我可以這樣做:

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

這也沒有得到我想要的:

  • 輸入 3.141 結果為 3.14(好)
  • 輸入 3.1 得到 3.10(不好,我想要 3.1)
  • 輸入 3 結果為 3.00(不好,我想要 3)

我該如何解決這個問題?

您可以使用字符串格式化的一般格式類型。

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

你可以簡單地這樣做

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

看看這個合不合適!

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

輪廓

注意:不適用於負數

如果您只希望它用於打印,則以下工作。

from decimal import Decimal

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

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

但是,這會將 3.0 之類的數字變成 3。(不清楚您是否想要這種行為)

你的意思是這樣的?

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

此解決方案更基於字符串

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM