I’ve only recently realised that ints are capped in PHP and if you’re on a 32 bit system they are quite limited. So, I have a few questions regarding numbers in PHP:
If an int becomes too big, am I right in saying PHP converts it to a float? This is from the PHP manual:
Can floats be bigger than ints because they use shorthand versions like 5.0E+19? If so, what is the biggest float possible on a 32 bit system?
If you had a BIGINT field in MySQL and you try inserting a variable that PHP has converted to something like 5.0E+19, is it clever enough to convert it to the full number?
Given the limitation on ints, is casting as (int) not a good idea unless you know the number will be less than PHP_INT_SIZE? Is it better to use regex to remove non-0-9 and treat it as a string?
If you need to perform arithmetic on large numbers, do you need to rely on a third party lib?
Generally, you’re better off storing large numbers as strings in PHP. I’ve never needed it so I’ll let someone else answer the best way to perform arithmetic on them.
Me neither but I like to get my head round these things. Thanks for your example. I would love to hear from someone regarding the MySQL question. It seems MySQL can handle bigger numbers better but PHP may cause you to lose data.
Yes, big numbers will be converted to floats but some precision can be lost.
Yes, MySQL will convert 5.0E+19 to the full number. The problem is this number might not be the one you want if you lost precision earlier due to PHP conversion to float and its limited bit depth. Keep large numbers as strings and use the extensions logic_earth mentioned to perform arithmetics on them.
BTW, you can use DECIMAL in MySQL to store even greater number than BIGINT allows.
Usually once you get to numbers that big the loss of precision is irrelevant. The number will have sufficient digits on the front that are accurate that you will not need to care about what the remaining digits are. With 5.000000000000000e+19 does it really matter whether the number is 1000 bigger or smaller than the exact value? In most cases the answer would be NO.
Yes, I guess in the real world it is rare you’d need the precision. I’ve been using PHP for over 10 years and never had the problem. I was just interested in how it worked.