What's the best way to get the fractional part of a float in PHP?

前端 未结 10 861
不思量自难忘°
不思量自难忘° 2020-11-30 05:45

How would you find the fractional part of a floating point number in PHP?

For example, if I have the value 1.25, I want to return 0.25.

相关标签:
10条回答
  • 2020-11-30 06:04

    If if the number is negative, you'll have to do this:

     $x = abs($x) - floor(abs($x));
    
    0 讨论(0)
  • 2020-11-30 06:05
    $x = fmod($x, 1);
    

    Here's a demo:

    <?php
    $x = 25.3333;
    $x = fmod($x, 1);
    var_dump($x);
    

    Should ouptut

    double(0.3333)
    

    Credit.

    0 讨论(0)
  • 2020-11-30 06:07

    To stop the confusion on this page actually this is the best answer, which is fast and works for both positive and negative values of $x:

    $frac=($x<0) ? $x-ceil($x) : $x-floor($x);
    

    I ran speed tests of 10 million computations on PHP 7.2.15 and even though both solutions give the same results, fmod is slower than floor/ceil.

    $frac=($x<0) ? $x-ceil($x) : $x-floor($x); -> 490-510 ms (depending on the sign of $x)

    $frac=fmod($x, 1); -> 590 - 1000 ms (depending on the value of $x)

    Whereas the actual empty loop itself takes 80 ms (which is included in above timings).

    Test script:

    $x=sqrt(2)-0.41421356237;
    
    $time_start = microtime(true);
    for ($i=0;$i<=9999999;$i++) {
        //$frac=fmod($x, 1); // version a
        $frac=($x<0) ? $x-ceil($x) : $x-floor($x); // version b
    }
    $time_end = microtime(true);
    
    $time = $time_end - $time_start;
    
    0 讨论(0)
  • 2020-11-30 06:13

    Some of the preceding answers are partial. This, I believe, is what you need to handle all situations:

    function getDecimalPart($floatNum) {
        return abs($floatNum - intval($floatNum));
    }
    
    $decimalPart = getDecimalPart($floatNum);
    
    0 讨论(0)
提交回复
热议问题