PHP Unexpected value when comparing floating values

0

I already saw the problem of floating comparisons with integers and decimals. Here is explained in the red box: link

To solve this we have the library: BCMath arbitrary precision math : link

And supposedly the function would come from luxury: int bccomp (string $ left_operand, string $ right_operand [ int $ scale = 0])

Well ... It Does not Work !!!! I have developed an ecommercer that until now the discounts were percents of whole numbers.

Now the discounts can be: - Entire percentages - Percentages with decimals - Amount with decimals

And at the time of seeing in a matrix if there is a discount comes the problem. Try this code:

var_dump(0.61);
var_dump(0.00);
var_dump(bccomp(0.61, 0));

It is assumed that 0.61 is greater than 0

Well, the function returns this:

float (0.61) float (0) int (0)

PHP 7.1.22 tells me that 61 cents and nothing is the same.

What am I doing wrong? In my code everything is varied and in the comparisons I always force the values:

if (bccomp((real)$matrizpvp[2], 0.00) !== 0)
if (bccomp((real)$matrizpvp[2], 0) !== 0)

I have tried both ways, even putting the zero in a variable.

    
asked by Manu Burrero Sánchez 28.09.2018 в 10:31
source

3 answers

2

You are missing the third parameter, which indicates the number of decimals to use in the comparison, by not including it only compares the value int.

  

bccomp (string $ left_operand, string $ right_operand [ int $ scale]   )

echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

You can see the example in this link

    
answered by 28.09.2018 в 10:37
0

I solved momentarily with:

if ((real)$matrizpvp[2] > 0)

Which does not convince me, I'm left with many doubts and there are many points where these conditions are used.

    
answered by 28.09.2018 в 10:34
0

My mom, what a rookie mistake, 1000 times I changed and tried the code and I did not see it, it should be a mandatory parameter so that carajotes like me do not miss, here is the complete example of the error:

<?php
Echo "<br><b>Mal uso de la función:</b><br>";           

$a= 0.61;
$b= 0.00;

$a = (real)$a;
$b = (real)$b;

echo $a . " (Valor de A)<br>"; 
echo $b . " (Valor de B)<br>"; 
echo bccomp($a, $b) . " (Devolución de bccomp)<br>"; 

var_dump($a);
var_dump($b);
var_dump(bccomp($a, $b));

Echo "<br><b>Buen uso de la función:</b><br>";          

$a= 0.61;
$b= 0.00;

$a = (real)$a;
$b = (real)$b;

echo $a . " (Valor de A)<br>"; 
echo $b . " (Valor de B)<br>"; 
echo bccomp($a, $b, 2) . " (Devolución de bccomp)<br>"; 

var_dump($a);
var_dump($b);
var_dump(bccomp($a, $b, 2));

/*Devuelve:

Mal uso de la función:
0.61 (Valor de A)
0 (Valor de B)
0 (Devolución de bccomp)
float(0.61) float(0) int(0) 

Buen uso de la función:
0.61 (Valor de A)
0 (Valor de B)
1 (Devolución de bccomp)
float(0.61) float(0) int(1)
*/

?>
    
answered by 28.09.2018 в 10:57