Number formatting (php)

9

I created a function cotacaoDolar(); which returns at the end:

return str_replace(",",".",$texto_dolar);

And the result appears here:

echo  $i['sellingStatus'][0]['currentPrice'][0]['__value__'] * cotacaoDolar();

How do I format the value ( ['_ value _'] ) quoted above?

You're like this: R$ 271.309389 ou R$ 1119.2445

The right one would be: R$ 271,30 ou R$ 1.119,24

    
asked by anonymous 01.04.2014 / 19:51

4 answers

13

Use the function number_format () ;

$valor = 12345678900;

echo number_format($valor,2,",",".");
// 123.245.678.900,00
    
01.04.2014 / 19:58
7

In php5.3 a class already exists for currency formatting. The first argument of NumberFormatter() is the currency that is based on the ISO 4217

$valores = array('530077.99','31459.89', '2899.39', '600.51', '13', '9', '0.25');
$formatter = new NumberFormatter('pt_BR',  NumberFormatter::CURRENCY);
foreach($valores as $item){
    echo  $formatter->formatCurrency($item, 'BRL') . '<br>';
}

The reverse process, converting a currency value to the pure value to write to the bank for example, can be done using the parseCurrency

$arr=array('R$530.077,99','R$31.459,89','R$2.899,39','R$600,51','R$13,00','R$9,00','R$0,25');

foreach($arr as $item){
    echo  $formatter->parseCurrency($item, $valor_puro) . '<br>';
}

Example

    
01.04.2014 / 20:02
6

Use the number_format function. The function by default returns in American format, so the need to pass 2 parameters, in this case the "," and ".".

echo 'R$' . number_format($num, 2, ',', '.');
    
01.04.2014 / 19:56
4

Use number_format :

<?php

$number = 1234.56;

// Notação Inglesa (padrão)
$english_format_number = number_format($number);
// 1,234

// Notação Francesa
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// Notação Inglesa sem separador de milhar
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>
    
01.04.2014 / 19:55