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.
Advertisement
Answer
Using str_replace()
to remove the dots is not overkill.
$string_number = '1.512.523,55'; // NOTE: You don't really have to use floatval() here, it's just to prove that it's a legitimate float value. $number = floatval(str_replace(',', '.', str_replace('.', '', $string_number))); // At this point, $number is a "natural" float. print $number;
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.