Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does PHP transform 15+ digit long integer on output [duplicate]

Tags:

php

integer

Why does echo 100000000000000; output 1.0E+14 and not 100000000000000?

This kind of transformation of integers on output happens only for integers that are 15 digits long and longer.

like image 287
Emanuil Rusev Avatar asked Mar 15 '13 16:03

Emanuil Rusev


People also ask

What is the limit of PHP integer value?

PHP Integers An integer data type is a non-decimal number between -2147483648 and 2147483647 in 32 bit systems, and between -9223372036854775808 and 9223372036854775807 in 64 bit systems. A value greater (or lower) than this, will be stored as float, because it exceeds the limit of an integer.

How do I echo an integer in PHP?

There are a number of ways to "convert" an integer to a string in PHP. The traditional computer science way would be to cast the variable as a string: $int = 5; $int_as_string = (string) $int; echo $int . ' is a '.

How to assign integer value in PHP?

PHP doesn't by default make a variable integer or string, if you want to set default value, then simply write $myvariable = 0; and this will assign and make variable an integer type.

How can I get the last two digits of a number in PHP?

Now array[0] and array[1] is the first two digits. array[array. length-1] and array[array. length] are the last two.


2 Answers

PHP will convert an integer to float if it is bigger than PHP_INT_MAX. For 32-bit systems this is 2147483647.

The answer to the questions is related to the string representation of floats in PHP.

If the exponent in the scientific notation is bigger than 13 or smaller than -4, PHP will use scientific representation when printing floats.

Examples:

echo 0.0001; // 0.0001;

echo 0.00001; // 1.0E-5

// 14 digits
echo 10000000000000; // 10000000000000

// 15 digits
echo 100000000000000; // 1.0E+14

See float vs. double precision

like image 163
Haralan Dobrev Avatar answered Oct 12 '22 22:10

Haralan Dobrev


That number is too big to fit into a 32 bit integer so PHP is storing it in a float.

See the integer overflow section in the php manual.

On the off chance that you need really big integers, look into GMP.

like image 24
Jacob Parker Avatar answered Oct 13 '22 00:10

Jacob Parker