I was wondering it there is a simple way to convert a float, for example 0.25
, into a string without the point/float, i.e. like 025
.
Is it possible? I'm searching for something that works for all floats. Thanks.
Asked
Active
Viewed 1,912 times
1

Alessandro Peca
- 873
- 1
- 15
- 40
-
2Could you try just removing characters? https://stackoverflow.com/a/3559600/4510954 – ElConrado Apr 10 '19 at 07:36
-
1What's the use-case? Under what you're asking for, the float values `12.50` and `1.25` would both be converted into `125`. Is that really what you want? – Mark Dickinson Apr 10 '19 at 08:52
3 Answers
3
You could use regex replacement with re.sub in the case where there are both commas and decimal points. re.sub()
replaces all occurrences of a pattern in the string by the replacement repl. If the pattern isn’t found, the string is returned unchanged.
import re
number = '999,123,456.345'
filtered = re.sub('[.,]', '', number)
print(filtered)
Output
999123456345

nathancy
- 42,661
- 14
- 115
- 137
2
Using str.replace()
:
def float2str(s):
return str(s).replace('.', '')
print(float2str(0.25))
OUTPUT:
025
Using reduce:
from functools import reduce
x = "3,766.989"
replacements = (',', '', '.', '')
print(reduce(lambda s, sep: s.replace(sep, ''), replacements, x))
OUTPUT:
3766989

DirtyBit
- 16,613
- 4
- 34
- 55