Search code examples
phpmathrounding

PHP - Possible to round a decimal to any specified decimal even 0.64 or 0.11


I have a number, lets say 45.67 and I need to round it to the nearest .43

eg. 45.67 rounds down to 45.43. Or if I have another number 34.98 and I need to round it to the nearest .13. It should round up to 35.13.

Is this possible with PHP?

I have spent the good part of an afternoon trying to solve this, but any google search comes up with only being able to round to quarters as in .25 or halves .5. it looks as though it is not possible. AI GPT or Bard cannot solve it either.


Solution

  • How about this:

    function roundFrac($val, $frac)
    {
        return round($val - $frac) + $frac;
    }
    
    echo roundFrac(45.67, 0.43); // 45.43
    echo roundFrac(34.98, 0.13); // 35.13