problem with decimals and thousands

1

I have this edition for an update, where the value is a decimal number with 15.2 (fifteen whole digits and 2 decimals) and replacement comma (,) by period (.) to add it to a database.

    include ("connection_upload_csv.php");

    if(isset($_POST["submit"]))
    {
        $file = $_FILES['file']['tmp_name'];
        $handle = fopen($file, "r");
        $c = 0;
        while(($filesop = fgetcsv($handle, 1000, ";")) !== false)
        {       {
            $entrega_importe = (str_replace(',', '.', $filesop[14]));


 $sql = mysql_query("INSERT INTO " . TABLE_ENTREGAS . " (entrega_importe)
VALUES ('$entrega_importe')");
                        }

but I have a problem if the number comes from the origin like this:

1,044.00

I need you to replace the comma of the decimal point, and if the number contains a point of the thousands erase it, or replace by ('') but only for the thousands.

the result after the update should be:

1044.00

how can I do the str_replace so that it makes those two changes in the same variable. $entrega_importe =

    
asked by Ivan Diaz Perez 12.03.2018 в 14:20
source

2 answers

2

Try using regular expressions, here is an example

//Aquí remuevo los separadores de miles . que te llegan
$entrega_importe = preg_replace('/\.(\d{1,3})/', '$1', $filesop[14]);
//Aquí remuevo el separador de los decimales ,
$entrega_importe = preg_replace('/,(\d{2})$/','.$1', $entrega_importe);

If $ filesop had the value: 12.003.123.12.25 I would format it to 1200312312.25 which I understood was what you were looking for.

    
answered by 12.03.2018 / 14:38
source
1

If the data arrives as a string, the conversion of the point and the comma can be done by passing arrays as parameters in str_replace ():

$valor = "1.044,00";
$old = ['.', ','];
$new = ['', '.'];
$valor = str_replace($old, $new, $valor);

From then on it already depends if you need to convert it to float or format it as a number and leave it as a string:

$valor = floatval($valor);
    
answered by 12.03.2018 в 14:34