PHP Float Value WorkAround

Please reference: PHP Unit Floating Value Issue

As for the Question, I wrote the following code. It can be done differently or with less code than this.

The following will help when either of the two given values ​​is less than 1 with decimal values. Is this good practice?

<?php

        $First_Value = 0.005;
        $Second_Value = 0.1;

        // Check the First Value for Decimal
        $First_Whole = floor($First_Value);  // 0
        $First_Fraction = $First_Value - $First_Whole; // .005

        // Check the Second Value for Decimal
        $Second_Whole = floor($Second_Value); // 0
        $Second_Fraction = $Second_Value - $Second_Whole; // .1

        // Multiply with 100 becaus ethe decimal is restricted to 3 digit so multiply with 100 works
        if(($First_Whole == 0) || ($Second_Whole == 0)){
            $First_Value = $First_Value*100; // 0.5
            $Second_Value = $Second_Value*100; // 10
        }

        echo $tableCount = $Second_Value / $First_Value; // 20
?>

      

0


source to share


1 answer


You don't need to do any calculations. just do the last split.

...
$value1 = .005;
$value2 = .1;

echo $value1 / $value2;

      

leads to 20

If you are trying to get only 2 decimal places, you can use the post-division number format. If you are trying to format before division, you can still specify the format. If, however, you cannot then not just multiply both numbers by 1000 (three decimal places)% by 1 and minus the difference of the mod from the actual. which will give you 3 in this case, divide back by 1000



[EDIT]

to get the remainder do the following example

...
$v = .0055;
$d = .1;

$a = $d/$v;
$s = $a % ceil($a);
$r = $a - $s;

      

answer = .18181818181818181 ...

+1


source







All Articles