Problem with float numbers in php

0

How about? I know it's a very talked about topic but I can not find a solution if you can lend me a hand. I have an application in which I calculate the VAT and as the products I offer have different VAT I have decided to add the amount and assign it in an array whose key is the VAT that is applied I give an example:

$array_suma_productos = [
  "12.5" => 29,
  "21.4" => "30",                                                        
];

I clarify that the VAT is not the real right now I do not remember, the fact is that the key is in string and I have to pass it to float so I did the following

foreach ($array_suma_productos as $key => $value) {
    $key=(float)$key;
    $total[]=calcular_iva($key,$value);
}

The problem is that $ key gives me zero when applying float, any solution?

Thanks in advance

    
asked by john_7573 15.11.2018 в 21:41
source

2 answers

0

Solved, the problem was how to keep the $ key used the following format:

$array_suma_productos['"'.$imp.'"']='valor de la variable';

the correct way is this:

$imp=(string)$imp;                            
$array_suma_productos[$imp]='valor de la variable';
    
answered by 16.11.2018 / 15:14
source
1

Welcome to Stackoverflow.

I do not know exactly what kind of final result you want, but if you do this for example:

foreach ($array_suma_productos as $key => $value) { 
    $total[]=$value*((float)$key)/100; 
} 

You will have this array in $total :

Array
(
    [0] => 3.625
    [1] => 6.42
)

If you want the VAT to be associated with the amount, you can do so:

foreach ($array_suma_productos as $key => $value) {
    $total[$value]=$value*((float)$key)/100;   
}

You'll have:

Array
(
    [29] => 3.625
    [30] => 6.42
)

And, if you want all the data, you add a new key with the calculated VAT:

foreach ($array_suma_productos as $key => $value) {
    $iva=$value*((float)$key)/100;
    $total[]=array($key,$value,$iva);   
}

You'll have:

Array
(
    [0] => Array
        (
            [0] => 12.5
            [1] => 29
            [2] => 3.625
        )

    [1] => Array
        (
            [0] => 21.4
            [1] => 30
            [2] => 6.42
        )

)

If you persist in wanting to use a function. Then:

  • Do not do the conversion in the loop, but in the function
  • Verify the treatment you give to the values in it

For example:

function calcular_iva($key,$value){
    $key=(float)$key; //conversión aquí
    return $value*((float)$key)/100;
}

And in the for, simply this:

foreach ($array_suma_productos as $key => $value) { 
    $total[]=calcular_iva($key,$value); 
} 
    
answered by 15.11.2018 в 22:08