简体   繁体   English

在 Python 3.x 中显示到两个小数点……但也没有这些小数点(如果适用) - 如何?

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

In Python 3.8 I'm trying to get a float value to display as follows:在 Python 3.8 中,我试图让一个浮点值显示如下:

  • If the number has more than 2 decimal points, it should be rounded to 2 decimal points.如果数字的小数点超过 2 位,则应四舍五入到小数点后 2 位。
  • If the number has one decimal point, it should display as only one decimal point.如果数字有一位小数,它应该只显示一位小数。
  • If the number has no decimal points, it should not display with a decimal point at all.如果数字没有小数点,则根本不应该显示小数点。

I'm aware of "round".我知道“圆”。 If I have this program:如果我有这个程序:

print ('input a number')
chuu = float(input())
chuu = round(chuu,2)
print (chuu)
  • Input 3.141 results in 3.14 (good)输入 3.141 结果为 3.14(好)
  • Input 3.1 results in 3.1 (good)输入 3.1 结果为 3.1(好)
  • Input 3 results in 3.0 (bad, I want 3)输入 3 结果为 3.0(不好,我想要 3)

I'm also aware that I can do this:我也知道我可以这样做:

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

This doesn't get what I want either:这也没有得到我想要的:

  • Input 3.141 results in 3.14 (good)输入 3.141 结果为 3.14(好)
  • Input 3.1 results in 3.10 (bad, I want 3.1)输入 3.1 得到 3.10(不好,我想要 3.1)
  • Input 3 results in 3.00 (bad, I want 3)输入 3 结果为 3.00(不好,我想要 3)

How do I resolve this issue?我该如何解决这个问题?

You can use the general format types of string formatting.您可以使用字符串格式化的一般格式类型。

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

you could simply do this你可以简单地这样做

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

See if this fits!看看这个合不合适!

chuu = 4.1111             #works for 4, 4.1111, 4.1

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

Edit:编辑:

@Mark very accurately pointed out a potential flaw in the above approach. @Mark 非常准确地指出了上述方法中的一个潜在缺陷。

Here's a modified approach that supports many possibilities including what @mark pointed out.这是一种修改后的方法,它支持许多可能性,包括@mark 指出的内容。

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

Caters to all these possibilities:满足所有这些可能性:

#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

轮廓

Note: Doesn't work with negative numbers注意:不适用于负数

If you only want it for printing, the following works.如果您只希望它用于打印,则以下工作。

from decimal import Decimal

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

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

However, this will turn numbers like 3.0 into just 3. (Not clear if you wanted that behavior or not)但是,这会将 3.0 之类的数字变成 3。(不清楚您是否想要这种行为)

You mean something like this?你的意思是这样的?

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

This solution is more string based此解决方案更基于字符串

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