Set precision for a float number in PHP

前端 未结 5 1812
难免孤独
难免孤独 2020-11-28 15:12

I get a number from database and this number might be either float or int.

I need to set the decimal precision of the number to 3

相关标签:
5条回答
  • 2020-11-28 15:38

    See this answer for more details.

    function numberPrecision($number, $decimals = 0)
    {
        $negation = ($number < 0) ? (-1) : 1;
        $coefficient = pow(10, $decimals);
        return $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
    }
    
    0 讨论(0)
  • 2020-11-28 15:41

    If I understand correctly, you would not want rounding to occur and you would want the precision to be 3.

    So the idea is to use number_format() for a precision of 4 and then remove the last digit:

    $number = '1518845.756789';
    $precision = 3;
    
    echo substr(number_format($number, $precision+1, '.', ''), 0, -1);
    

    Will display:

    1518845.756
    

    rather than:

    1518845.757
    

    Links : number_format() , substr()

    0 讨论(0)
  • 2020-11-28 15:52

    You can use number_format() to achieve this:

    echo number_format((float) $number, $precision, '.', ''); 
    

    This would convert 1518845.756789 to 1518845.757.

    But if you just want to cut off the number of decimal places short to 3, and not round, then you can do the following:

    $number = intval($number * ($p = pow(10, $precision))) / $p;
    

    It may look intimidating at first, but the concept is really simple. You have a number, you multiply it by 103 (it becomes 1518845756.789), cast it to an integer so everything after the 3 decimal places is removed (becomes 1518845756), and then divide the result by 103 (becomes 1518845.756).

    Demo

    0 讨论(0)
  • 2020-11-28 15:54

    Its sound like floor with decimals. So you can try something like

    floor($number*1000)/1000
    
    0 讨论(0)
  • 2020-11-28 15:58
    $num=5.1239;
    $testnum=intval($num*1000)/1000;
    echo $testnum; //return 5.123
    
    0 讨论(0)
提交回复
热议问题