In Python 3.8 I'm trying to get a float value to display as follows:
I'm aware of "round". If I have this program:
print ('input a number')
chuu = float(input())
chuu = round(chuu,2)
print (chuu)
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:
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))
@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
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.