在Python 3.x中显示到两个小数点......但如果适用的话,也可以不显示这些小数点 - 怎么做?

问题描述 投票:0回答:1

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

如何解决这个问题?

python python-3.x rounding
1个回答
3
投票

你可以简单地这样做

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

6
投票

你可以使用字符串格式的一般格式类型。

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

2
投票

如果你只想把它打印出来,下面的方法可以用。

from decimal import Decimal

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

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

然而,这将把像3.0这样的数字变成只有3。 (不清楚你是否想要这种行为)


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

Profile

注意: 不适用于负数


1
投票

你是说像这样的东西?

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

1
投票

这个解决方案是基于字符串的

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
© www.soinside.com 2019 - 2024. All rights reserved.