user5790923
user5790923

Reputation:

How can I remove ".0" of float numbers?

Say I have a float number. If it is an integer (e.g. 1.0, 9.0, 36.0), I want to remove the ".0 (the decimal point and zero)" and write to stdout. For example, the result will be 1, 9, 36. If the float number is a rational number such as 2.5335 and 95.5893, I want the output to be as it was inputted, meaning 2.5335 and 95.5893. Is there a smart way to do this?

Only whether the number has .0 or other digits at decimal places does matter. I can say my question is this: how can I know whether or not a float number is actually an integer?

I want to use this to decide directory names. For example, if I input 9.0 and 2.45, make two directories, dir9 and dir2.45.

Upvotes: 11

Views: 41080

Answers (7)

Mark P
Mark P

Reputation: 31

Further to 'MD. Ferdous Ibne Abu Bakar''s answer, should you have a string this function would work:

val = str(5.0)
def remove_zero_float(val):
    if float(val) == int(float(val)):
        val = int(float(val))
    return val

Output: 5

Upvotes: 0

num = 5.0
if float(num) == int(num):
    num = int(num)

Output: 5

Upvotes: 1

RinSlow
RinSlow

Reputation: 139

You can do that with fstrings like

print(f'{1.0:g},{1.2:g}')  # Output: 1,1.2

Upvotes: 8

reticivis
reticivis

Reputation: 616

you can use string formatting

>>> "%g" % 1.1
'1.1'
>>> "%g" % 1.0
'1'

Upvotes: 11

rambi
rambi

Reputation: 1259

You can combine the 2 previous answers :

formatNumber = lambda n: n if n%1 else int(n)
>>>formatNumber(5)
5

>>>formatNumber(5.23)
5.23

>>>formatNumber(6.0)
6

Upvotes: 8

Adil Warsi
Adil Warsi

Reputation: 551

just type int(number) example :

int(3.0)

returns

3

Upvotes: -4

nshoo
nshoo

Reputation: 977

Here's a function to format your numbers the way you want them:

def formatNumber(num):
  if num % 1 == 0:
    return int(num)
  else:
    return num

For example:

formatNumber(3.11111)

returns

3.11111


formatNumber(3.0)

returns

3

Upvotes: 26

Related Questions