简体   繁体   中英

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:

  • If the number has more than 2 decimal points, it should be rounded to 2 decimal points.
  • 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)
  • Input 3.1 results in 3.1 (good)
  • Input 3 results in 3.0 (bad, I want 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)
  • Input 3.1 results in 3.10 (bad, I want 3.1)
  • Input 3 results in 3.00 (bad, I want 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.

Here's a modified approach that supports many possibilities including what @mark pointed out.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM