+ 2
how can i make a float disappear?
I am making a simple calculator, when I try to calculate the root of 4 the answer is 2.0 and i want the answer to be 2. thanks a lot if needed this is my code https://drive.google.com/open?id=17nrCmyT34nAe1JYUdZJb7Tq7XV2bxd35
8 Respostas
+ 5
Hi use int() function.
+ 5
def sqrt_(n):
sq = sqrt(n)
if sq%1 == 0:
return int(sq)
return sq
+ 4
Convert to string, you can use regEx to search if it has zero after decimal, split at decimal(.), take the first part, convert back to integer.
+ 4
Hubert Dudek , int() won't restrict it to numbers only having zeros after decimal rather it'll convert every float to the nearest int but Hans Ten katen mentioned that it should convert it to int only if it has zeros after decimal.
+ 2
this is only when i have a .0 after the number.
+ 2
The link you shared seems to redirect to a login page instead a code.
+ 1
This won't work for more than 15 decimals (at least on SL) but here you go.
def test(n):
return int(n) if int(n)==n else n
print(test(2)) # 2
print(test(2.0)) # 2
print(test(2.1)) # 2.1
print(test(2.00)) # 2
print(test(2.01)) # 2.01
0
Use floor function of math module.