开发者

php- floating point number shown in exponential form

开发者 https://www.devze.com 2023-03-18 09:18 出处:网络
Could anyone please tell me why this happens, $a= 0.000022 echo $a // 2开发者_开发知识库.2E-5 What I want to see is 0.000022 not 2.2E-5The exponential form is the internal one use by every (?) pro

Could anyone please tell me why this happens,

$a  = 0.000022

echo $a // 2开发者_开发知识库.2E-5

What I want to see is 0.000022 not 2.2E-5


The exponential form is the internal one use by every (?) programming language (at least CPUs "sees" floats this way). Use sprintf() to format the output

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

See Manual: sprintf() about more information about the format parameter.


use number_format() function

echo number_format($a,6,'.',',');

the result would be 0.000022


Try this:

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); 
}


You can apply the solution below if you want to filter data for such cases (for example, data from SQLite is returned in exponential form).

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([])        === []           );
0

精彩评论

暂无评论...
验证码 换一张
取 消