I am trying to make a function to which passing a $cantidad
, it must return the percentage of that amount over the total , $total
.
function obtenerPorcentaje($cantidad) {
$total = (float)$row['total']; // Obtener total de la base de datos
$porcentaje = ((float)$cantidad * 100) / $total; // Regla de tres
$porcentaje = round($porcentaje, 0); // Quitar los decimales
return $porcentaje;
}
The problem is that it always returns 0
o INF
(infinity), but if instead of (float)$row['total']
I put for example: 5000.758294
, it works.
So that you can help me, I will explain everything:
$row['total']
is a value stored in a database in a FLOAT field , and doing thevar_dump
of this variable I get:string(11) "2938.483920"
, and using the (float) before the variable I get:float(2938.483920)
.$cantidad
receives the value with which the percentage is going to be calculated and in this case it is:string(10) "374.839284"
, but with the (float) it returns tofloat(374.839284)
- The operations are a rule of three , where the $value is multiplied by
100
and divided by the$cantidad
. - I am using
round()
because I represent the percentage using ProgressBar, to which I must pass an integer.
I am sure that the problem comes from the numbers , which are obtained with an incorrect format or something like that, since as I have mentioned, just changing (float)$row['total']
to a number already works perfectly .
If you use $row['total'] without passing it as a parameter, it should be declared global somewhere else. The most correct thing would be that you pass the total as a parameter of your function
or that you declare your rows as global (definitely not recommended)
and that the function that calls this, also has the $rows as global.
Eventually you can also pass the rows as a parameter
Your code should have sent you a warning that the $rows variable was not defined by the way... follow the interpreter's clues.