JavaScript 1e16 * Math.random () equivalent to PHP

2

I have this line of code that when executed in the console generates random numbers of 16 characters:

1e16 * Math.random()

When executing you can give this kind of results:

1e16 * Math.random() //8988522134496624

As you can see, it generates the 16-digit number. My question is, how can I achieve this in PHP?

for now I have this and nothing that works:

function random() {
   return rand(1e16, 100000000000000) / 1e16;
}
echo random();

// this is the error

  

Warning: rand () expects parameter 1 to be integer, float given in   C: \ xampp \ htdocs \ demo \ test.php on line 3 '

    
asked by Rafael Dorado 26.11.2018 в 00:50
source

3 answers

0

It turns out that the tests I was doing in XAMPP gave me that error that I wrote above, the solution without so much code is:

<?php
 $random = rand(1e16, 100000000000000);
 echo $random; //8988522134496624
<?
    
answered by 04.12.2018 / 03:36
source
4

There are several ways to do it.

For example:

Combining rand and pow

$digits = 16;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);

Exit:

4532665451057255

Combining mt_rand and pow

$digits = 16;
echo mt_rand(pow(10, $digits-1), pow(10, $digits)-1);

Exit:

2518521800171584

Using a loop for

function randomNumber($length) {
    $result = '';
    for($i = 0; $i < $length; $i++) {
        $result .= mt_rand(0, 9);
    }
    return $result;
}
echo randomNumber(16);

Exit:

1033651704719868

For more details you can see this SO response in English

    
answered by 26.11.2018 в 02:17
0

you can do it like this:

function random() {
   return rand(100000000000000,1e16);
}
echo random();

function random_16d() {
  $rand   = 0;
  for ($i = 0; $i<15; $i++) {
    $rand .= mt_rand(0,9);
  }
 return $rand;
}

echo random_16d()
    
answered by 26.11.2018 в 02:19