duandu8202 2017-12-20 18:55 采纳率: 0%
浏览 16

从数字中取出X小数位数

I have let's say 0.00001004 or 0.00001

I am trying to choose and how decimal places to prune off and turn both of those so it returns 0.00001 both times.

I do not want it to round the number in anyway.

I've tried this but it is not giving me the desired results.

function decimalFix($number, $decimals) { 
   return floatval(bcdiv($number, 1, $decimals)); 
}

echo decimalFix(0.00001, 5); // returns "0"

Does anyone know what I can do? I can't have any rounding involved and I need it to return it as a float and not a string.

  • 写回答

2条回答 默认 最新

  • dongsicheng5262 2017-12-20 19:01
    关注

    There's a function that does exactly this in the first comment on the PHP documentation for floor(). I'll copy it here in case it disappears from there, but credits go to seppili_:

    function floordec($zahl,$decimals=2){    
         return floor($zahl*pow(10,$decimals))/pow(10,$decimals);
    }
    

    Use it like:

    $number = 0.00001004;
    
    $rounded = floordec($number, 5);
    var_dump($rounded); // float(0.00001)
    

    Edit: There's a comment further down on that page by Leon Grdic that warns about float precision and offers this updated version:

    function floordec($value,$decimals=2){    
        return floor($value*pow(10,$decimals)+0.5)/pow(10,$decimals);
    }
    

    Usage is the same.

    评论

报告相同问题?