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.
Asked
Active
Viewed 6,926 times
0
-
2Show what you have tried. (and you mean *period*, not comma) – Idos Jul 23 '16 at 17:25
-
I haven't tried anything because I don't know where to begin – PunkZebra Jul 23 '16 at 17:26
-
3`str(number).replace('.','')` – Aran-Fey Jul 23 '16 at 17:27
-
`number = number.translate(None, '.').lstrip('0')` – Idos Jul 23 '16 at 17:27
-
2*What have you tried* to read on the Python documentation, then? – OneCricketeer Jul 23 '16 at 17:29
-
I'd also done 'int(str(number).replace('.', ''))' but I searched for other ways and I found this function of the _math_ module that may interests you http://stackoverflow.com/questions/6681743/splitting-a-number-into-the-integer-and-decimal-parts-in-python – Stéphane Jul 23 '16 at 17:37
2 Answers
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