How not to round off the value to the next digit using PHP

The PHP round() function often rounds a number to the next digit which is correct if the third digit is greater than or equal to 5 however sometimes we don’t want the number to go to the next digit like in cases of calculating tax or VAT (in the UK).
Use the following function if you don’t want the number to be rounded off to the next number.

function floordec($value,$precision,$separator)
{
       $numberpart=explode($separator,$value);
       $numberpart[1]=substr_replace($numberpart[1],$separator,$precision,0);
       if($numberpart[0]>=0)
       {
         $numberpart[1]=floor($numberpart[1]);
       }
       else
       {
         $numberpart[1]=ceil($numberpart[1]);
       }
       $ceil_number= array($numberpart[0],$numberpart[1]);
       return implode($separator,$ceil_number);
}

echo floordec(3.489,2,"."); // Result will be 3.48
Please follow and like us:

Be the first to comment

Leave a Reply

Your email address will not be published.


*