How to convert scientific notation to string with full number

4

What php function should I use to do this type of conversion?

  

Converter: 1.3388383658903E + 18 for: 1338838365890273563

I tried this, but it did not work:

echo sprintf(sprintf('%%.%df', 0), '1.3388383658903E+18');

And that too:

echo rtrim(sprintf('%.0F', $value), '0');
  

edited so far to better explain the problem:

See this example with serialize :

$a = array('valor' => 1338838365890273563);
$serializado = serialize($a);

How can I fix this when doing unserialize($serializado) ?

Example in ideone

    
asked by anonymous 04.10.2016 / 19:26

2 answers

3

About numerical precision:

The question asks something that is not possible, convert 1.3388383658903E+18 to 1338838365890273563 .

The 1.3388383658903E+18 notation is accurate only for the real-readable string.

If you need the original value, convert to string before from serialize :

$a = array('valor' => '1338838365890273563' );
$serializado = serialize($a);

See the quotation marks in the value. Note that even in your code the literal value is written:

$valor = 1338838365890273563;

Internally PHP will save only what fits in the float. So it is essential that you treat the data as string throughout the "life" of the script.

If you need more numerical capacity, you can use bc_math and GMP, but in your case probably strings are a better solution. More details in the PHP manual:

  

link


About scientific notation display:

Just this:

echo sprintf( '%f', 1.3388383658903E+18 );

Or this, of course:

$numero = '1.3388383658903E+18'; // o ideal mesmo é sem aspas
echo sprintf( '%f', $numero );

If you prefer without the decimals:

echo sprintf( '%.0f', 1.3388383658903E+18 );

See working at IDEONE .

If it's just to show on the screen:

Then you do not need the echo, just use printf instead of sprintf :

printf( '%.0f', 1.3388383658903E+18 );

I kept sprintf in the original example, because it's usually what you'll use if you save the value in a string, or concatenate with something else.


Observations:

  • We can not use %d , because integer capacity is broken;

  • Using .0 before f is to say that we want zero decimal places;

  • There is no need for quotes in value, since the nE+n format is already understood as number by language of course. But look at IDEONE that the problem is not this one, because PHP does cast anyway.

  • It makes no difference in our case, but be careful, because %f and %F are different things. Both are float, but one of them is locale-aware (which changes the decimal sign according to the region).

05.10.2016 / 23:02
-6

You add up the scientific notation plus one (1) that it will return the number in double / float.

Ex:

$notation = "1.3388383658903E+18";
echo $notation + 1;

This is because PHP is a poorly typed language.

    
05.10.2016 / 21:46