Number format to N significant digits in PHP

I would like to format (round) float (double) numbers to say, for example, 2 significant digits:

1        => 1
11       => 11
111      => 110
119      => 120
0.11     => 0.11
0.00011  => 0.00011
0.000111 => 0.00011

Thus, arbitrary accuracy remains the same

I expect there is some nice feature for the already built-in, but not yet found

I pointed to How to round to the nearest significant digit in php , which is close, but does not work for N significant digits, and I don’t do what it does with numbers 0.000XXX

+4
source share
2 answers

To get a number rounded to n significant digits, you need to find the number size to the power of ten and subtract from n.

This is great for simple rounding:

function sigFig($value, $digits)
{
    if ($value == 0) {
        $decimalPlaces = $digits - 1;
    } elseif ($value < 0) {
        $decimalPlaces = $digits - floor(log10($value * -1)) - 1;
    } else {
        $decimalPlaces = $digits - floor(log10($value)) - 1;
    }

    $answer = round($value, $decimalPlaces);
    return $answer;
}

:
0.0001234567 0.0001235
123456.7 123500

, 10 4 , 10,00 , .

, :

function sigFig($value, $digits)
{
    if ($value == 0) {
        $decimalPlaces = $digits - 1;
    } elseif ($value < 0) {
        $decimalPlaces = $digits - floor(log10($value * -1)) - 1;
    } else {
        $decimalPlaces = $digits - floor(log10($value)) - 1;
    }

    $answer = ($decimalPlaces > 0) ?
        number_format($value, $decimalPlaces) : round($value, $decimalPlaces);
    return $answer;
}

1 1.000

+1

:

public static function roundRate($rate, $digits)
{
    $mod = pow(10, intval(round(log10($rate))));
    $mod = $mod / pow(10, $digits);
    $answer = ((int)($rate / $mod)) * $mod;
    return $answer;
}
+1

All Articles