在PHP中将数字格式设置为N个有效数字 [英] Format number to N significant digits in PHP

查看:209
本文介绍了在PHP中将数字格式设置为N个有效数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想格式化(四舍五入)浮点(双精度)数字,例如,这样说2个有效数字:

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

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

所以任意精度保持不变

我希望它已经内置了一些不错的功能,但到目前为止找不到任何功能

I expect there is some nice function for it already built in, but could not find any so far

有人指出我如何四舍五入下降到php中最接近的有效数字,该数字很接近,但不适用于N个有效数字,我不确定0.000XXX数字有什么作用

I was pointed to How to round down to the nearest significant figure in php, which is close but doesn't work for N significant digits and I'm not sure what it does with 0.000XXX numbers

推荐答案

要将数字四舍五入为n个有效数字,您需要找到数字的大小(以10的幂为单位),然后从n中减去.

To get a number rounded to n significant figures you need to find the size of the number in powers of ten, and subtract that from n.

这对于简单的四舍五入非常有用:

This works fine 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

This will give the following:
0.0001234567 returns 0.0001235
123456.7 returns 123500

但是,例如10到4个有效数字之类的值应严格表示为10.00,以表示该值的精确度.

However a value such as 10 to four significant figures should strictly be represented as 10.00 to signify the precision to which the value is known.

如果这是所需的输出,则可以使用以下内容:

If this is the desired output you can use the following:

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

Now 1 is displayed as 1.000

这篇关于在PHP中将数字格式设置为N个有效数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆