Problem with number_format when saving in mysql

0

I have a problem with storing numbers with decimals in mysql.

It turns out that to show it in an input I convert the amount to Spanish format with thousands separated by. and decimals for, and I do it like this:

number_format($Precio,2,",",".");

and to store it in mysql I change the, for a point like this:

'".str_replace(",",".",$_POST["Precio"])."'

But I run into the problem when the value has thousands since the answer comes with a. separating the thousands with what if the value is 1,000,30 saves me 1.00 in mysql.

I thought about deleting the. with str_replace before changing the, for a point, but I find a solution a little dirty.

Is there any more elegant way to do this?

    
asked by Killpe 06.02.2018 в 12:43
source

1 answer

1

You can perfectly remove the points from the string and replace the comma with the decimal point. It is a valid and perhaps the least expensive solution.

If you think ugly , you can create a beautiful function with only two lines:

function strToDecimal($valor){
    $decimal = str_replace(',', '.', str_replace('.', '', $valor));
    return $decimal;
} 

Let's try it:

SEE DEMO IN REXTESTER

$numero = "1.000,30";
$decimal=strToDecimal($numero);
echo $decimal.PHP_EOL;

$numero = "10.000,99";
$decimal=strToDecimal($numero);
echo $decimal.PHP_EOL;

$numero = "9.999.999,99";
$decimal=strToDecimal($numero);
echo $decimal.PHP_EOL;

Exit:

1000.30
10000.99
9999999.99

There you have totally valid values to insert as DECIMAL in any database manager.

NOTE:

This type of functions can be incorporated into a Clase utilitarian%, in programs where we need to do this type of operations in various scenarios.

    
answered by 06.02.2018 в 15:18