Floatify: whats it do and why we use it
May 20, 2015 | matthew-townsend
Floatify or rather how it’s been used in some templates, has prompted readers of the blog to question it – and thanks to those who have emailed asking, we’ve put this article together to explain 🙂
What is floatify
Floatify is a reasonably simple, built in xmerge function that takes a piece of data and will try force that data to be converted – and returned – as a floating point number instead.
Its base xmerge function is:
How does floatify work
When floatify is called, it will go through each part of a nominated piece of data and filter out anything that is not a digit (0,1,2,3,5,6,7,8,9) and then return the result as a floating point number – you know those guys with the decimal places.
The returned result will also maintain any decimal places in the original data as well.
Example with variables:
<:let myMoney = ‘$550.67 AUD’:>
# You should see: 550.67 as the returned result, noting the rest of the string has been stripped out.
The more technical function for how it’s achieved is actually something you’ve likely come across already in standard templates and something that often raises questions from people. Before it was a standard function, here was the function you still sporadically see littered throughout templates:
<:let floatify=lambda val: float(filter(lambda x: x.isdigit() or x in ‘.-‘, str(val))):>