以指数形式显示的浮点数


php- floating point number shown in exponential form

谁能告诉我为什么会这样,

$a  = 0.000022
echo $a // 2.2E-5

我想看到的是0.000022而不是2.2E-5

指数形式是每个(?)编程语言使用的内部形式(至少cpu"看到"这种方式浮动)。使用sprintf()对输出进行格式化

echo sprintf('%f', $a);
// or (if you want to limit the number of fractional digits to lets say 6
echo sprintf('%.6f', $a);

关于格式参数的更多信息请参见Manual: sprintf()

use number_format() function

echo number_format($a,6,'.',',');
结果将是0.000022

试试这个:

function f2s(float $f) {
    $s = (string)$f;
    if (!strpos($s,"E")) return $s;
    list($be,$ae)= explode("E",$s);
    $fs = "%.".(string)(strlen(explode(".",$be)[1])+(abs($ae)-1))."f";
    return sprintf($fs,$f); 
}

如果您想过滤这种情况下的数据(例如,来自SQLite的数据以指数形式返回),可以应用下面的解决方案。

function exponencial_string_normalize($value) {
  if (is_string($value) && is_numeric($value))
    if ($value !== (string)(int)$value && $value[0] !== '0')
      return rtrim(substr(number_format($value, 14), 0, -1), '0'); # with suppression of the rounding effect
  return $value;
}
var_dump( exponencial_string_normalize(-1)        === -1           );
var_dump( exponencial_string_normalize(-1.1)      === -1.1         );
var_dump( exponencial_string_normalize('1234')    === '1234'       ); # normal notation      (is_numeric === true)
var_dump( exponencial_string_normalize('1.23e-6') === '0.00000123' ); # exponential notation (is_numeric === true)
var_dump( exponencial_string_normalize('4.56e-6') === '0.00000456' ); # exponential notation (is_numeric === true)
var_dump( exponencial_string_normalize('01234')   === '01234'      ); # octal notation       (is_numeric === true) !!! conversion to number will be incorrect
var_dump( exponencial_string_normalize('0b101')   === '0b101'      ); # binary notation      (is_numeric === false)
var_dump( exponencial_string_normalize('0x123')   === '0x123'      ); # hexadecimal notation (is_numeric === false)
var_dump( exponencial_string_normalize('а123')    === 'а123'       );
var_dump( exponencial_string_normalize('123а')    === '123а'       );
var_dump( exponencial_string_normalize(true)      === true         );
var_dump( exponencial_string_normalize(false)     === false        );
var_dump( exponencial_string_normalize(null)      === null         );
var_dump( exponencial_string_normalize([])        === []           );