irovder
(Ivan)
January 12, 2023, 9:44pm
1
Hi, using Scrape I get some price as string with whitespace, which I need as float.
How to remove it or convert the price to float?
# ok:
{% set price = '1 199' %}
{{ price }}
{{ price.replace(" ", "") | float}}
# the problem:
{% set price = states.sensor.tv_heureka.state %}
{{ price }}
# price == '1 199'
{{ price.replace(" ", "") }}
{{ price.replace(' ', '') }}
# conversion to float not possible
Result type: string
# ok:
1 199
1199.0
# the problem:
1 199
# price == '1 199'
1 199
1 199
# conversion to float not possible
123
(Taras)
January 12, 2023, 9:58pm
2
Try this:
{{ (states('sensor.tv_heuteka') | slugify).replace('_', '') | float(0) }}
I don’t have the means to test it so I can’t guarantee it will work.
irovder
(Ivan)
January 12, 2023, 10:42pm
3
123:
slugify
It does not work with the second string, but thanks for your effort anyway!
123
(Taras)
January 12, 2023, 10:58pm
4
I wish I could be of more help but I can’t simulate the data you have.
I tried this but the
is displayed literally whereas in your example it’s displayed as a space.
{% set price = '1 199' %}
{{ price }}
{{ (price | slugify).replace('_', '') | float(0) }}
irovder
(Ivan)
January 13, 2023, 9:55am
5
That’s true - I can reproduce your output. But when the string value comes from the website it is not working. I will try to analyze and compare both strings if I can see what’s the difference.
justone
January 13, 2023, 10:28am
6
perhaps a regex replace sort of
{{ (price) | regex_replace(find='([^0-9].)', replace='') | float(0) }}
additional note: you don’t want to remove what you don’t know, you want to keep what’s wanted. Sort of looking from the other side onto the problem.
Troon
(Troon)
January 13, 2023, 10:47am
7
or try {{ price|urlencode }}
and remove the converted non-breaking space, probably %C2%A0
.
1 Like
irovder
(Ivan)
January 13, 2023, 3:42pm
8
Thank you, I also thought about using regex. Unfortunatelly I was getting 199 instead of 1199 with that code but after some tweaking I am sure it would be ok.
irovder
(Ivan)
January 13, 2023, 3:44pm
9
Thank you it worked!
{{ price|urlencode | replace("%C2%A0", "") }}
gives 1199 as I needed.
1 Like
Troon
(Troon)
January 13, 2023, 3:55pm
10
Good stuff. The regex is also a good plan, although should have been:
{{ (price) | regex_replace(find='[^0-9]', replace='') | float(0) }}
The original version was removing a group of “not-a-digit” followed by anything: in this case our magic space and the following 1.