PHP Division Float Value WorkAround

2019-09-17 03:12发布

Kindly refer: PHP Division Float Value Issue

With reference to the Question I have wrote the following code. Can this be done in different way or less code than this.?

The following will help when any of the two given value are lesser than 1 with decimal values. Is this a 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
?>

标签: php math decimal
1条回答
闹够了就滚
2楼-- · 2019-09-17 03:22

You don't need to do any of that calculation. just do the last division.

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

echo $value1 / $value2;

results in 20

If you are trying to get just 2 decimals you can use number format after dividing. If you are trying to format before dividing then you should still be able to number format. If however, you cannot then why not just multiply both numbers by 1000 (three decimals) % by 1 and minus the difference of the mod from the actual. that 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...

查看更多
登录 后发表回答