Convert Currency Values to Decimal?

Asked

Viewed 3,812 times

0

I have three values that are being passed via POST to be recorded in the database, I try to record the data but it records with wrong values. The data is like this:

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

In the database they are recorded as 1.00,1.00 and 0.00

I used str_replace to remove the comma, but it didn’t work.

$estoque->valorbruto = str_replace(',','.',substr($v1,2));
  • What is the field type in the table? Decimal (9.2) for example?

  • But why not use the float field of the database, to record right?

  • The fields are decimal(13,2)

  • Float would look better?

  • your str_replace is not removing the miler separator... this is causing the problem.

  • Solved. Vlw.

  • 4

    Float is not suitable for storing monetary values, see that answer and Best kind of data to work with money?

  • I’ll read this @rray always used the float, I think I’m wrong rsrsrrs thank you!

Show 3 more comments

2 answers

2

Just forgot to remove the stitch.

It should be like this

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

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

Unit of thousands

In computation there are no markers for thousand units. This markup is merely visual. The point represents decimal, so you get unexpected results like the one presented in the question.

Tip: decimal places

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

It would be "eating" 3333333, are 7 houses. In a system with many transactions this is a huge hole in the accounts. But it’s not mandatory because it varies with each business Logic. Just be aware in modeling a business model that requires greater precision.

1

SQL does not work with a comma. It separates the decimal using a dot(.). First vc must remove the point from the string q takes and then replace the comma by a dot.

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

Simplifying: Step one, remove the mile point. ex: $valorRecebidoSemMilhar = str_replace('.', '', $valorRecebido); 2º replace the decimal comma by a point. ex: $valorCorreto = str_replace(',', '.', $valorRecebidoSemMilhar);

Browser other questions tagged

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