Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round down to the nearest significant figure in php

Is there any slick way to round down to the nearest significant figure in php?

So:

0->0
9->9
10->10
17->10
77->70
114->100
745->700
1200->1000

?

like image 589
Kzqai Avatar asked Apr 29 '11 16:04

Kzqai


3 Answers

$numbers = array(1, 9, 14, 53, 112, 725, 1001, 1200);
foreach($numbers as $number) {
    printf('%d => %d'
            , $number
            , $number - $number % pow(10, floor(log10($number)))
            );
    echo "\n";
}

Unfortunately this fails horribly when $number is 0, but it does produce the expected result for positive integers. And it is a math-only solution.

like image 64
Arjan Avatar answered Nov 02 '22 11:11

Arjan


Here's a pure math solution. This is also a more flexible solution if you ever wanted to round up or down, and not just down. And it works on 0 :)

if($num === 0) return 0;
$digits = (int)(log10($num));
$num = (pow(10, $digits)) * floor($num/(pow(10, $digits)));

You could replace floor with round or ceil. Actually, if you wanted to round to the nearest, you could simplify the third line even more.

$num = round($num, -$digits);
like image 4
andrewtweber Avatar answered Nov 02 '22 09:11

andrewtweber


If you do want to have a mathy solution, try this:

function floorToFirst($int) {
    if (0 === $int) return 0;

    $nearest = pow(10, floor(log($int, 10)));
    return floor($int / $nearest) * $nearest;
}
like image 3
NikiC Avatar answered Nov 02 '22 10:11

NikiC