I've been searching for a while now, but what I can find is not what I search for. I need to convert an integer value, that may be very huge, to a string. Sounds easy: "$var"? No, because this can lead to the E+ representation of the number.
<?php
$var = 10000000000000000000000000;
echo $var."\n";
echo "'$var'\n";
echo (string) $var."\n";
echo strval($var);
?>
1.0E+25
'1.0E+25'
1.0E+25
1.0E+25
How can I make the output be 10000000000000000000000000 instead?
This is not stored as an integer by PHP, but a float, this is why you end up with 1.0E+25 instead of 10000000000000000000000000.
It's sadly not possible to use that as an integer value in PHP, as PHP cannot save an integer of that size. If this comes from database then it will be a string and you can do with it whatever you want. If you store it elsewhere then store it as a string.
Your alternative is to store it as a float and take that into account at all times, though that requires additional conversions and handling in places.
It's also been suggested to use GNU Multiple Precision, but that's not enabled in PHP by default.
$int=gmp_init("10000000000000000000000000");
$string=gmp_strval($int);
echo $string;
UPDATE:
Found the next post:
// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015
// full conversion
printf('%0.0f',pow(2,50)); // 112589906846624
echo sprintf('%0.0f',pow(2,50)); // 112589906846624
Use printf or sprintf.
I'm facing this problem when getting facebook id and find it in MySQL.
And after half hour, i found this work perfectly!
Insert this line to your php script:
ini_set('precision',30);
From: https://forums.phpfreaks.com/topic/125907-solved-convert-big-number-to-string/#entry651084
The integer number you like to express:
$var = 10000000000000000000000000;
is not available on your system. It's too large and therefore PHP converts it into a float which will change the number (32 bit system example):
10000000000000000905969664
Common limits are:
yours : 10 000 000 000 000 000 000 000 000
32 bit: 2 147 483 648
64 bit: 9 223 372 036 854 775 808
The change of the value is called floating point precision, the PHP manual about integers will tell you about the integer limit and the floats page about floating point precision (see the big red warning). Depending on which system you are, you can compile PHP with the ranges your application needs or you must use another datatype, for example with the gmp library which is able to pick strings as integer numbers and handle them.
The following example shows just output, but you can do multiplications etc.:
$r = gmp_init('10000000000000000000000000');
echo gmp_strval($r);
Hope this is helpful.
Related
I made this function. It seemed it's working but when it comes to 20 digits number, the return value was 19. I'm wondering why this problem happen..
My function
function sumDigits($n) {
return strlen($n);
}
echo sumDigits(100); //3
echo sumDigits(1000); //4
echo sumDigits(12345); //5
echo sumDigits(1000000000); //10
echo sumDigits(145874589632); //12
echo sumDigits(0); //1
echo sumDigits(12345698745254856320); //19 <-- Why not 20?
Can you please somebody explain for me?
Thank you so much.
First, I would point out that the name of your function is misleading, as you are not really summing the values of the digits, but are counting the digits. So I would call your function countDigits instead of sumDigits.
The reason why it doesn't work for large numbers, is that the string representation will switch to scientific notation, so you're actually getting the length of "1.2345698745255E+19" not of "12345698745254856320"
If you are only interested in integers, you will get better results with the logarithm:
function countDigits($n) {
return ceil(log10($n));
}
For numbers that have decimals, there is no good solution, since the precision of 64-bit floating pointing point numbers is limited to about 16 significant digits, so even if you provide more digits, the trailing decimals will be dropped -- this has nothing to do with your function, but with the precision of the number itself. For instance, you'll find that these two literals are equal:
if (1.123456789123456789123456789 == 1.12345678912345678) echo "equal";
Because you function parameter is an integer, exceeding the limit.
If you dump it, it actually shows the following:
1.2345698745255E+19 - which is 19 letters.
If you would do the following, it will return 20 - mind the quotes, which declares the input as string.
echo sumDigits("12345698745254856320"); //19 <-- Why not 20? -> now will be 20
As per documentation, strlen() expects a string so a cast happens. With default settings you get 1.2345698745255E+19:
var_dump((string)12345698745254856320);
string(19) "1.2345698745255E+19"
The root issue is that PHP converts your integer literal to float because it exceeds PHP_INT_MAX so it cannot be represented as integer:
var_dump(12345698745254856320, PHP_INT_MAX);
In 64-bit PHP:
float(1.2345698745254857E+19)
int(9223372036854775807)
You could change display settings to avoid E notation but you've already lost precision at this point.
Computer languages that store integers as a fixed amount of bytes do not allow arbitrary precision. Your best chance is to switch to strings:
var_dump('12345698745254856320', strlen('12345698745254856320'));
string(20) "12345698745254856320"
int(20)
... and optionally use an arbitrary precision library such as BCMath or GMP if you need actual maths.
It's also important to consider that this kind of issues is sometimes a symptom that your input data is not really meant to be an integer but just a very long digit-only string.
So I got a really long string, made by a calculator.
$string='483451102828322427131269442894636268716773727170';
$result=(8902543901+$string)*($string/93.189)/($string)+55643907015.57895461;
echo $result;
This outputs 5.1878558931668E+45
So now my question is. How can I output the whole string, without that nasty E+45?
PHP on a 64 bit machine can only accurately calculate number up until 9223372036854775807. As soon as you calculate with numbers higher than that, php will switch to floats which may loose some of it's precision, especially when you use divisions.
There's an extension for php that will allow you to make calculations based on string, called BCMath.
Example:
$string = '483451102828322427131269442894636268716773727170';
$result = bcadd($string, 8902543901);
echo $result;
bcadd() is for additions, bcdiv() for divisions and bcmul() for multiplying.
You can't print exact value because you are using calculation, so this $string becomes a number (float in this case) and all numbers have limited precision.
If you want to do operations on big numbers you should use BCMath
However if you want to display it without scientific notation you can do it using:
echo sprintf("%f",$result);
or
echo sprintf("%.0f",$result);
if you want to omit decimal part
When i make the following multiplication in PHP:
$ret = 1.0 * 0.000000001;
i get the result: 1.0E-9
I want to convert this result into the normal decimal notation, how can i do this?
sprintf('%f',$ret) doesn't work, it returns 0.000000. Overflow?
sprintf('%f',$ret) doesn't work, it returns 0.000000. Overflow?
sprintf works, however you miss some point here.
0.000000 is not overflow. It's just that sprintf for the %f modifier uses 6 digits per default. Also please take care that %f is locale aware, %F is probably better suited.
You might want to use more digits, e.g. let's say 4 000 000 (four million):
$ php -r "printf('%.4000000F', 1*0.000000001);"
Notice: printf(): Requested precision of 4000000 digits was truncated to PHP maximum of 53 digits in Command line code on line 1
Call Stack:
0.0001 319080 1. {main}() Command line code:0
0.0001 319200 2. printf() Command line code:1
0.00000000100000000000000006228159145777985641889706869
As this example shows, there is not only a common value (6 digits) but also a maximum (probably depended on the computer system PHP executes on), here truncated to 53 digits in my case as the warning shows.
Because of your question I'd say you want to display:
0.000000001
Which are nine digits, so you need to write it that way:
sprintf('%.9F',$ret)
However, you might want to do this:
rtrim(sprintf('%.20F', $ret), '0');
which will remove zeroes from the right afterwards:
0.000000001
Hope this is helpful.
You need to add precision specifier (how many decimal digits should be displayed for floating-point numbers). Something like this:
echo sprintf('%.10f',$ret); // 0.0000000010
If you have no idea what number you should specify, just give it a big number and combine it with rtrim().
echo rtrim(sprintf('%.20f', $ret), '0'); // 0.000000001
The code above will strip any 0's from the end of the string.
I suggest the use BCMath for more accuracy when you are calculating with decimal numbers. That makes sure that you actually get the results you want.
To print what you want, you should specify the precision and use %.9f, since it defaults to displaying 6 decimal numbers. That makes it something like this (just like bsdnoobz already said):
sprintf('%.9f',$ret);
To align to your system's settings and limitations, you could use serialize_precision to get the most accurate result possible.
echo rtrim(sprintf('%.'.ini_get('serialize_precision').'f', $ret));
I do not recommend using the non-locale aware %F since your question only makes sense for display purposes. Respecting locale makes for a better UX.
the topic pretty much describes what we would like to accomplish.
a) start with a possible range of integers, for example, 1 to 10000.
b) take any md5 hash, run it thru this algo.
c) result that pops out will be an integer between 1 to 10000.
we are open to using another hashing method too.
the flow would ideally look like this:
string -> md5(string) -> algo(md5(string),range) -> resulting integer within range
is something like this possible?
final note: the range will always start with 1.
if you have an answer, feel free to post just the general idea, or if you so desire, php snippet works too :)
thanks!
Since MD5 (and SHA-1, etc.) will give you 128 bits of data (in PHP, you'll get it in hexadecimal string notation, so you need to convert it to an integer first). That number modulo 10000 will give you your integer.
Note however that many different hashes will convert to the same integer; this is unavoidable with any sort of conversion to your integer range, as the modulo operation essentially maps a larger set of numbers (in this case, 128 bits, that is numbers from 0 to 340,282,366,920,938,463,463,374,607,431,768,211,456) to a smaller set of numbers (less than 17 bits, numbers from 1 to 100,000).
since the range that we want will always start at 1, the following works great. all credit goes to Piskvor, as he was the one who provided the basic idea of how to go at this.
the code below seams to accomplish what we want. please chime in if this can be (not the code, its just for reference, but if the idea) improved at all. running the code below will result in 6305 / 10000 unique results. that in our case is good enough.
<?
$final=array();
$range=10000;
for($i=1;$i<=$range;$i++){
$string='this is my test string - attempt #'.$i;
echo 'initial string: '.$string.PHP_EOL;
$crc32=crc32($string);
echo 'crc32 of string: '.$crc32.PHP_EOL;
$postalgo=$crc32%$range;
echo 'post algo: '.$postalgo.PHP_EOL;
if(!in_array($postalgo,$final)){
$final[]=$postalgo;
}
}
echo 'unique results for '.($i-1).' attempts: '.count($final).PHP_EOL;
?>
enjoy!
In PHP I have a 64 bit number which represents tasks that must be completed. A second 64 bit number represents the tasks which have been completed:
$pack_code = 1001111100100000000000000011111101001111100100000000000000011111
$veri_code = 0000000000000000000000000001110000000000000000000000000000111110
I need to compare the two and provide a percentage of tasks completed figure. I could loop through both and find how many bits are set, but I don't know if this is the fastest way?
Assuming that these are actually strings, perhaps something like:
$pack_code = '1001111100100000000000000011111101001111100100000000000000011111';
$veri_code = '0000000000000000000000000001110000000000000000000000000000111110';
$matches = array_intersect_assoc(str_split($pack_code),str_split($veri_code));
$finished_matches = array_intersect($matches,array(1));
$percentage = (count($finished_matches) / 64) * 100
Because you're getting the numbers as hex strings instead of ones and zeros, you'll need to do a bit of extra work.
PHP does not reliably support numbers over 32 bits as integers. 64-bit support requires being compiled and running on a 64-bit machine. This means that attempts to represent a 64-bit integer may fail depending on your environment. For this reason, it will be important to ensure that PHP only ever deals with these numbers as strings. This won't be hard, as hex strings coming out of the database will be, well, strings, not ints.
There are a few options here. The first would be using the GMP extension's gmp_xor function, which performs a bitwise-XOR operation on two numbers. The resulting number will have bits turned on when the two numbers have opposing bits in that location, and off when the two numbers have identical bits in that location. Then it's just a matter of counting the bits to get the remaining task count.
Another option would be transforming the number-as-a-string into a string of ones and zeros, as you've represented in your question. If you have GMP, you can use gmp_init to read it as a base-16 number, and use gmp_strval to return it as a base-2 number.
If you don't have GMP, this function provided in another answer (scroll to "Step 2") can accurately transform a string-as-number into anything between base-2 and 36. It will be slower than using GMP.
In both of these cases, you'd end up with a string of ones and zeros and can use code like that posted by #Mark Baker to get the difference.
Optimization in this case is not worth of considering. I'm 100% sure that you don't really care whether your scrip will be generated 0.00000014 sec. faster, am I right?
Just loop through each bit of that number, compare it with another and you're done.
Remember words of Donald Knuth:
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
This code utilizes the GNU Multi Precision library, which is supported by PHP, and since it is implemented in C, should be fast enough, and supports arbitrary precision.
$pack_code = gmp_init("1001111100100000000000000011111101001111100100000000000000011111", 2);
$veri_code = gmp_init("0000000000000000000000000001110000000000000000000000000000111110", 2);
$number_of_different_bits = gmp_popcount(gmp_xor($pack_code, $veri_code));
$a = 11111;
echo sprintf('%032b',$a)."\n";
$b = 12345;
echo sprintf('%032b',$b)."\n";
$c = $a & $b;
echo sprintf('%032b',$c)."\n";
$n=0;
while($c)
{
$n += $c & 1;
$c = $c >> 1;
}
echo $n."\n";
Output:
00000000000000000010101101100111
00000000000000000011000000111001
00000000000000000010000000100001
3
Given your PHP-setuo can handle 64bit, this can be easily extended.
If not you can sidestep this restriction using GNU Multiple Precision
You could also split up the HEx-Representation and then operate on those coresponding parts parts instead. As you need just the local fact of 1 or 0 and not which number actually is represented! I think that would solve your problem best.
For example:
0xF1A35C and 0xD546C1
you just compare the binary version of F and D, 1 and 5, A and 4, ...