Format string/float for PHP currency

Asked

Viewed 1,736 times

1

I am doing reports in PHP and I have a column of value, only this column can come values with OR commas point. When it comes to displaying the value, I need you to show it in the form of cash. Example of some values of how it is in the database:

0,0123
1.7481
0.4875
,14571

Example of how I need you to show in the report:

R$ 0,01
R$ 1,74
R$ 0,49
R$ 0,15

I can’t develop any function that suits me in these cases, someone knows how I can develop this function?

  • As related by the author of the question this link does not solve his situation due to the values that it has in the database.

  • Try this return number_format(str_replace(',', '.', ',14571'), 2, ',', '.');, until it will work in these cases there passed, but if there is some other variation in your database, I believe that it will not work in the same way.

  • @Davidsantos I tried to use this example you gave me, only when there are values like 1,090.00 (one thousand and ninety), it returns R$1.09 (one real and nine cents) Thanks for the help!

  • Exactly @Huhifeku, as I mentioned if you had more data variations in your database it would not work. What you can do now that you already have a basis is a function that predicts all these variations, in this case there you passed me you can use so number_format(str_replace(['.', ','], ['', '.'], '1.090,00'), 2, ',', '.'); in this way it will replace the "point" by "nothing" and the "comma" by "point".

  • I’ve tried to do this way @Davidsantos and it worked for me for this specific case with 1.090,00, but the other values as for example the 1.7481, got 17.481,00

Show 1 more comment

2 answers

1


I hope that code is the solution

 $num = array("11.111.090,00" , "111.090,00", "090,00" , "0.4875");

 foreach ($num as $value) {
     if (strpos($value, "0") == 0){
         $value = str_replace(',', '.', $value);
         $value = number_format($value, 2, ',', '.');
         echo "R$ " . $value . " reais<br>";
     }else{
         $value = str_replace('.', '', $value);
         $value = str_replace(',', '.', $value);
         $value = number_format($value, 2, ',', '.');
         echo "R$ " . $value . " reais<br>";
     }
 }

0

// Informa as configurações locais que serão usadas na formatação.
// https://www.php.net/manual/en/function.setlocale.php
setlocale(LC_ALL, 'pt_BR');

/**
 * Formata como moeda um valor de acordo com as informações locais.
 * 
 * @param float $val valor que será formatado
 * @return string
 */
function currency(float $val): string
{
    $fmt = new NumberFormatter(setlocale(LC_MONETARY, null), NumberFormatter::CURRENCY);
    $locale = localeconv();
    return $fmt->formatCurrency($val, $locale['int_curr_symbol']);
}

echo currency(1200.99); // Retorna R$ 1.200,99

Browser other questions tagged

You are not signed in. Login or sign up in order to post.