Withdraw currency formatting and get only the number in PHP

7

I store the values of the products in the database as follows:

For example:

R$ 5.000,00

How do I do in PHP to make this number stay 5000? In other words, "deformat"?

Do you have any function that works for any number? Something like that?

    
asked by anonymous 09.08.2015 / 04:39

3 answers

9

I think it's the NumberFormatter::parseCurrency() you want.

$formatter = numfmt_create('pt_BR', NumberFormatter::CURRENCY);
var_dump(numfmt_parse_currency($formatter, "R$ 5.000,00", "BRL"));

I do not know if this module is available by default on the premises. I tried to run on the ideone and it was not.

You can do it manually as well, but it does give work and it's easy to miss something, do not handle a situation, solve badly formatted numbers, etc.

    
09.08.2015 / 04:53
3

You can do it in a simpler way too, see if it works:

setlocale(LC_MONETARY, 'pt_BR');
echo money_format('%i', $number) . "\n";  
    
09.08.2015 / 15:32
1

Conversion can be done simply like this:

$str = '99.999,99';
$str = str_replace('.', '', $str); // remove o ponto
echo str_replace(',', '.', $str); // troca a vírgula por ponto
// resulta em 99999.99

You can also use the numberformatter class , specifically the parsecurrency , if it is enabled in the environment where you want to run the code. I particularly prefer to sanitize with str_replace , as shown above since this class is usually not installed by default. In a shared hosting, for example, you will hardly be able to have this feature and in the end you will have to implement with str_replace or regex.

    
21.11.2016 / 07:28