Search code examples
phpnumbersdecimalfloor

Remove a decimal place in PHP


In PHP, I am getting numbers from a database with 3 decimal places. I want to remove the last decimal point. So 2.112 will become 2.11, 23.123 will become 23.12 and 123.267 will become 123.26. Its like doing a floor at a decimal level.


Solution

  • You can use number_format, you specify the number of decimal places as the second arugment.

    Example

    $number = 534.333;
    
    echo number_format($number,2) // outputs 534.33
    

    Or use round

    $number = 549.333;
    echo round($number, 2) // outputs 534.33
    

    Seems like substr is what solved the question in the end

    substr($number,0,-1); // everything besides the last decimal