0

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.

Diego V
  • 6,189
  • 7
  • 40
  • 45
PunkZebra
  • 119
  • 1
  • 5

2 Answers2

5

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
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • As far as I can see the command works with numbers with less than 12 digits after the comma, is there a way to have more digits returned? – PunkZebra Jul 23 '16 at 17:35
  • @Peterix [Floating Point Arithmetic: Issues and Limitations](https://docs.python.org/3/tutorial/floatingpoint.html#floating-point-arithmetic-issues-and-limitations) – Moses Koledoye Jul 23 '16 at 17:46
0

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.

jedwards
  • 29,432
  • 3
  • 65
  • 92