I have a list of prices with a comma for a decimal point and a dot as the thousand separator.
Some examples:
12,30
116,10
1.563,14
These come in this format from a third party. I want to convert them to floats and add them together.
What is the best way to do this? number_format doesn't seem to work with this format, and str_replace seems like overkill, as I have to do it more that once on each number.
Is there are better way? Thanks.
from PHP manual:
I would go down that route, and then convert from string to float - floatval
Using
str_replace()
to remove the dots is not overkill.This is almost certainly the least CPU-intensive way you can do this, and odds are that even if you use some fancy function to do it, that this is what it does under the hood.
Assuming they are in a file or array just do the replace as a batch (i.e. on all at once):
and then process the numbers from there taking full advantage of PHP's loosely typed nature.
This function is compatible for numbers with dots or commas as decimals
You could use the NumberFormatter class with its
parse
method.If you're using PHP5.3 or above, you can use numfmt_parse to do "a reversed number_format". If you're not, you stuck with replacing the occurrances with preg_replace/str_replace.