PHP Division Float Value WorkAround

北城以北 提交于 2019-12-11 19:59:38

问题


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
?>

回答1:


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...



来源:https://stackoverflow.com/questions/26100581/php-division-float-value-workaround

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!