How to correctly format a monetary value?

Asked

Viewed 691 times

4

I have a value that comes from the form that way:

R$ 1.500,95

I need him to stay that way:

R$ 1500,95

How to turn him into the second way? I need him to look completely the same as the way he was quoted.

3 answers

4


Remove the stitch and R$.

<?php

$moeda = "R$ 1.500,95";

// Com str_replace (Remove a string 'R$ ' e '.'
$valor = str_replace( array('R$ ', '.'),  '', $moeda);
echo $valor; //1550,95

// Com preg_replace (Remove tudo que for diferente de dígito e vírgula)
$valor = preg_replace( '/([^\d,])/',  '', $moeda);
$valor = preg_replace('/[,]+/', ',', $valor); // Fix para caso seja passado mais de 1 ","
echo $valor; //1550,95

?>
  • I updated the code to do it in two ways, with preg_replace or str_replace and also put a comment to have a better understanding.

  • Use the \d, you accept several ,, namely the 1550,,,,,95 would be returned exactly as is, would not be removed the , additional.

  • @Inkeliz, very right, I added the line $value = preg_replace('/[,]+/', ',', $value) to support this case, so the value will be the right way.

3

Another solution would be to remove only keep the whole numbers and divide them by 100.

$moeda = 'R$ 1.550,52';

$valor = preg_replace('/[^0-9]/', '', $moeda);    
$valor = bcdiv($valor, 100, 2);
$valor = strtr($valor, '.', ',');

echo $valor;

Upshot:

1550,52

That way, it would become:

string : 0e100 => 1,00
double : 0e100 => 0,00
string : 0x98 => 0,98
integer : 0x98 => 1,52
string : R$ 100.00 => 100,00
integer : 10000 => 100,00
double : 100.00 => 1,00
integer : 12345 => 123,45
string : 123.45 => 123,45
double : 123.45 => 123,45
string : 1a2b3c4d5e => 123,45
string : 123,45 => 123,45
string : R$ 123,45 => 123,45
string : 1 => 0,01
integer : 1 => 0,01

double : 9.0E+99 => 8999999999999999948859130765266355329578537025198862586562510896759102769772101980841694466750283776,00
integer : 9223372036854775807 => 92233720368547758,07

Test this.

This function, the way it is, has "problems" float, do not recommend to use for float/double. The float of 100.00 will be 1,00 and 100.01 will become 100,01, namely the 100.00 won’t go to 100,00, what may not be expected.

Obviously representation needs to contain the pennies, if it’s just R$ 1.550 will pass to 15,50. However, inform 1.550,00 no problem, just like 155000 or even 1a550b00.

If you find any other problem comment, because I really can’t imagine any, apart from the mentioned.

0

You can use the function preg_replace or str_replace, see below with preg_replace:

echo preg_replace('/^[0-9,]/', '', $valor);
// Saída: 1500,95
  • 2

    The output of this command over the string "1,500.95" results in ". 500.95". You are removing everything that starts with digits from 0 to 9 or comma.

Browser other questions tagged

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