PunkZebra
PunkZebra

Reputation: 119

Removing period from number in python

Given a real number between 0 and 1 (for example 0.2836) I want to return only the number without the dot (for example in this case from 0.2836 -> 2836 or 02836). I was trying to use python to do this but I just started and I need some help.

Upvotes: 0

Views: 7714

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78556

As long as you have a number, the following should do:

>>> number = 0.2836
>>> int(str(number).replace('.', ''))
2836

If a . is not found in the string, str.replace just returns the original string.

With more numbers:

>>> int(str(1).replace('.', ''))
1
>>> int(str(1.2).replace('.', ''))
12

Upvotes: 5

jedwards
jedwards

Reputation: 30210

The simplest way to remove an unwanted character from a strip is to call its .replace method with an empty string as the second argument:

x = str(123.45)
x = x.replace('.','')
print(x)                 # Prints 12345

Note, this would leave any leading zeros (i.e. 0.123 using this method would result in 0123)

If you know there are always, say, 4 numbers after the decimal (and in the case that there are less, you want trailing zeros), you could multiply the number by an appropriate factor first:

x = 123.4567
x *= 10000
x = str(int(x))          # Convert float to integer first, then to string
print(x)                 # Prints 1234567

There are other options, but this may point you in the right direction.

Upvotes: 0

Related Questions