Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Round function - round up to 2 dp?

Tags:

php

math

rounding

In PHP how would i round up the value 22.04496 so that it becomes 22.05? It seems that round(22.04496,2) = 22.04. Should it not be 22.05??

Thanks in advance

like image 766
Pjn2020 Avatar asked Dec 22 '22 12:12

Pjn2020


2 Answers

you can do it using ceil and multiplying and dividing by a power of 10.

echo ceil( 1.012345 * 1000)/1000;

1.013
like image 102
Gidon Wise Avatar answered Dec 24 '22 01:12

Gidon Wise


Do not do multiplication inside a ceil, floor or round function! You'll get floating point errors and it can be extremely unpredictable. To avoid this do:

function ceiling($value, $precision = 0) {
    $offset = 0.5;
    if ($precision !== 0)
        $offset /= pow(10, $precision);
    $final = round($value + $offset, $precision, PHP_ROUND_HALF_DOWN);
    return ($final == -0 ? 0 : $final);
}

For example ceiling(2.2200001, 2) will give 2.23.

Based on comments I've also added my floor function as this has similar problems:

function flooring($value, $precision = 0) {
    $offset = -0.5;
    if ($precision !== 0)
        $offset /= pow(10, $precision);
    $final = round($value + $offset, $precision, PHP_ROUND_HALF_UP);
    return ($final == -0 ? 0 : $final);
}
like image 41
Nico Westerdale Avatar answered Dec 24 '22 02:12

Nico Westerdale