Convert Currency Values to Decimal?

0

I have three values which are being passed via POST to be written to the database, I try to write the data but however it writes with wrong values. The data looks like this:

"valor_liquido": "R$1.000,00",
"valor_bruto": "R$1.000,00",
"valor_desconto": "R$0,00"

In the database they are written as 1.00,1.00 and

I used str_replace to remove the comma, but it did not work.

$estoque->valorbruto = str_replace(',','.',substr($v1,2));
    
asked by anonymous 17.08.2016 / 20:39

3 answers

1

Just forgot to remove the dot.

It should be like this

$estoque->valorbruto = str_replace('.', '', str_replace(',','.',substr($v1,2)));

The logic here is to first convert a comma to a point and then remove any other existing points.

Unit of thousands

In computing there are no markers for units of thousands. This marking is merely visual. The dot represents decimal, so you get unexpected results like the one you put in the question.

Hint: decimal places

One more tip, think carefully if you really want to keep monetary value with only 2 decimal places. In a division you can have .333333333, for example.

I would be "eating" 3333333, there are 7 houses. In a system with many transactions this is a huge gap in the accounts. But it is not mandatory as this varies with each business logic. Just be aware of modeling a business model that requires greater accuracy.

    
17.08.2016 / 22:41
0

try this:

$estoque->valorbruto = str_replace(',','.',str_replace('.', '', substr($v1,2)));
    
17.08.2016 / 20:53
0

SQL does not work with commas. It separates the decimal using a period (.). First you must remove the point of the string you receive and then replace the comma by the dot.

$valorFormatado = str_replace(',', '.', str_replace('.', '', $valorRecebido));

Simplifying: Step 1 Remove the point from the thousand. ex: $valorRecebidoSemMilhar = str_replace('.', '', $valorRecebido); 2º replace the decimal point by point. ex: $valorCorreto = str_replace(',', '.', $valorRecebidoSemMilhar);

    
17.08.2016 / 21:34