Error number_format

Asked

Viewed 303 times

0

Good evening, everyone.

I have this function to convert the American value to Brazilian

function Real($valor){
    $valor_real = number_format($valor,2, ',', '.');
    return $valor_real;
}

It works fine, but qdo will display houses with Ex. 1.250,00 it displays only 1,00

Can you help me?

I call function that way

R$ <?=Real($lnP['produto_atributo_preco']); ?>

In mysql the field is as DECIMAL(10,2) was as VARCHAR and yet this with this error

Thank you

  • In the bank this value is stored as "1250.00"? You can confirm this?

  • records @Andersoncarloswoss 1,250.00

2 answers

1

You cannot have it written to the bank like this 1,250.00 with DECIMAL(10,2) no, if you try to enter this value it will write to the bank 1.00 and when you apply its function to it it turns 1,00 here

For fields DECIMAL(10,2), at the time of the Insert has to be in these formats 1250.00 or 123456.00 or 1234567.89 etc, i.e., point separator (.) only in the decimal place.

Another solution ( a la gambiarra ) is to use Varchar for the field.

0


Commas as a thousand separator (American format) confuse the number_format. Remove and leave only the point as decimal separator:

$valor = '1,250.00';
$valor_real = number_format($valor,2, ',', '.');

echo $valor_real; // 1,00

$valor = str_replace(',', '', $valor); // 1250.00
$valor_real = number_format($valor,2, ',', '.');

echo $valor_real; // 1.250,00

Example

  • That’s right, Manow... I changed the decimal to sweep and function...

  • 1

    Varchar is gambiarra, not solution. Properly format the value before inserting into the bank with decimal column and you will have no problems.

Browser other questions tagged

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