99

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.

1
  • you could squeeze out the dots, then swap the comma for the dot and parse as float. That's only 2 replaces. That's not -terrible- unless you are doing tens-of-thousands of records at a shot
    – DampeS8N
    Commented Dec 1, 2010 at 14:34

9 Answers 9

156

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.

7
  • 6
    or just $number = str_replace( [',','.'], ['.'], $string_number )*1.0;
    – Jeff
    Commented Oct 25, 2017 at 17:56
  • 5
    @Jeff it's right trying to write the less lines of code as possible but I think code readability is a must in developing, even more important than writing less. Commented Dec 17, 2018 at 7:38
  • 3
    hmm, yeah, I seem to have overlooked the "Replacement order gotcha" which doesn't occur using mysql's replace. So the correct line is $number = str_replace( ['.',','], ['','.'], $string_number )*1.0;
    – Jeff
    Commented Apr 18, 2019 at 19:48
  • 3
    @manuman94, I don't think eliminating an unnecessary function call reduces readability.
    – Jeff
    Commented Apr 18, 2019 at 20:14
  • 1
    @Jeff I do haha but that's my opinion, of course. I appreciate your efforts to help community, it was only my point of view. Greetings! Commented Apr 18, 2019 at 21:56
58

This function is compatible for numbers with dots or commas as decimals

function floatvalue($val){
            $val = str_replace(",",".",$val);
            $val = preg_replace('/\.(?=.*\.)/', '', $val);
            return floatval($val);
}

This works for all kind of inputs (American or european style)

echo floatvalue('1.325.125,54'); // The output is 1325125.54
echo floatvalue('1,325,125.54'); // The output is 1325125.54
echo floatvalue('59,95');        // The output is 59.95
echo floatvalue('12.000,30');    // The output is 12000.30
echo floatvalue('12,000.30');    // The output is 12000.30
4
  • This is genius!
    – Adam
    Commented Oct 25, 2019 at 14:51
  • 1
    This should be the best answer, because it not broke an already decimal number. Commented Mar 10, 2021 at 23:00
  • 6
    Notice that it is not perfect, sending "1,500" will be converted to 1.5 rather than 1500
    – FrakyDale
    Commented Jan 26, 2022 at 18:39
  • 1
    This is because the function expects the number to be a decimal (float) number, so any punctuation will be threatened to transform the input to a float Commented Sep 6, 2022 at 17:28
23

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.

3
  • 1
    You need also PECL intl >= 1.0.0
    – riotera
    Commented Oct 13, 2012 at 20:48
  • 2
    "You need also PECL intl >= 1.0.0" No, it says you either need to have PHP 5.3 > or you need to install it via PECL intl package 1.0.0. PHP 5.3+ has the support built in. Commented Sep 4, 2015 at 18:51
  • 1
    You indeed will need to check whether intl extension is enabled. It is not builtin, it has to be either explicitly compiled in or installed as separate extension. Not all hosting providers install it with PHP.
    – cronfy
    Commented Apr 12, 2016 at 9:02
13

You could use the NumberFormatter class with its parse method.

2
  • 4
    Available in 5.3 or above only, just as a disclaimer. ;-)
    – Björn
    Commented Dec 1, 2010 at 14:40
  • ...and only w/ the intl extension compiled.
    – Ian Dunn
    Commented Jan 9, 2020 at 20:16
13

Might look excessive but will convert any given format no mater the locale:

function normalizeDecimal($val, int $precision = 4): string
{
    $input = str_replace(' ', '', $val);
    $number = str_replace(',', '.', $input);
    if (strpos($number, '.')) {
        $groups = explode('.', str_replace(',', '.', $number));
        $lastGroup = array_pop($groups);
        $number = implode('', $groups) . '.' . $lastGroup;
    }
    return bcadd($number, 0, $precision);
}

Output:

.12           -> 0.1200
123           -> 123.0000
123.91        -> 12345678.9100
123 456 78.91 -> 12345678.9100
123,456,78.91 -> 12345678.9100
123.456.78,91 -> 12345678.9100
123 456 78,91 -> 12345678.9100
1
  • 1
    Have you tried 1,000? 😂
    – bilogic
    Commented Sep 16, 2022 at 11:53
8

Assuming they are in a file or array just do the replace as a batch (i.e. on all at once):

$input = str_replace(array('.', ','), array('', '.'), $input); 

and then process the numbers from there taking full advantage of PHP's loosely typed nature.

1
  • I would also cast the type float like so $v = (float) str_replace(['.', ','], ['', '.'], $v); Commented Jun 30, 2019 at 3:45
1

from PHP manual:

str_replace — Replace all occurrences of the search string with the replacement string

I would go down that route, and then convert from string to float - floatval

0

For those who want an example of NumberFormatter :

    $test='2,345.67';

//  OOP Version
    $numberFormatter=new NumberFormatter('en-AU',NumberFormatter::DECIMAL);
    $number=$numberFormatter->parse($test);
    print $number;

//  Procedural Version
    $numberFormatter=numfmt_create('en_AU',NumberFormatter::DECIMAL);
    $number=numfmt_parse($numberFormatter,$test);
    print $number;

Of course your locale may very.

Not sure why anyone would opt for the procedural version.

Note that one major difference between NumberFormat and the str_replace type solutions is that NumberFormatter is sensitive to where you put your thousands and decimal characters; using 1,2345.00 won’t work.

0

You could use filter_var.

$floatNumber = (float) filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
3
  • var_dump((float) filter_var('223,5', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION)); results in float(2235)
    – Mike
    Commented Jul 28, 2022 at 10:17
  • In case other filters are needed, you can find them here: php.net/manual/en/filter.filters.sanitize.php
    – askepott
    Commented Aug 11, 2022 at 9:46
  • That is a decimal comma in the question. filter_var strips them off instead of interpreting.
    – micce
    Commented Apr 22 at 8:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.