I have the following line of code in javascript:
(Math.random() + "") * 1000000000000000000
which generates numbers like:
350303159372528000
I tried the same thing in PHP with this:
rand()*1000000000000000000
Which returns:
2.272e+21
I need to use PHP as the number generated will be stored as a SESSION variable and will be used by JavaScript later on.
How do I get PHP to force the number to be an int rather than a float?
EDIT PHP seems to struggle with this.
Would it work if I just generated the rand number in PHP saved it to the SESSION and then done the multiplying by 1000000000000000000 in JavaScript?
How would I go about this?
I'd recommend calling
PHP_INT_MAX
To see if your PHP installation can handle an integar that large. I'm guessing it can't which is why it is knocking it down to scientific notation.
I'd suggest converting your result to an int:
intval(rand()*1000000000000000000)
That said, see Kolink and Jeremy1026 answers for precision issues. If you only need an unique identifier, see Truth's answer.
Update: if you're using strings to represent your numbers, don't want or can't use an arbitrary precision library, and don't stricly need perfecly fair random numbers, you could generate smaller numbers and concat them together:
strval(rand()*999999999 + 1) . strval(rand()*1000000000)
(The +1 is to avoid a leading zero in your result; note also that your number will never have a single digit, but every other number is possible)
For a random number with (exactly) 18 digits, you can also use str_pad in the 2nd part, to fill it with leading zeros:
strval(rand(100000000,999999999)) .
str_pad(strval(rand(0,999999999)), 9, "0", STR_PAD_LEFT)
If you need a unique identifier (which is what it looks like you're trying to do), please use PHP's uniqid() function.
floor() / ceil() / round() / (int) / intval() will convert the number to int.
Also, rand() takes two arguments. If ints are supplied - it will return an integer
And printf() should take care of printing in the format you wish (printf('%d', $int) should do the trick)
In the end I solved the issue like this:
<?php
error_reporting(0);
function RandNumber($e){
for($i=0;$i<$e;$i++){
$rand = $rand . rand(0, 9);
}
return $rand;
}
echo RandNumber(18);
// Outputs a 18 digit random number
?>
Related
In php is there a way to give a unique hash from a string, but that the hash was made up from numbers only?
example:
return md5(234); // returns 098f6bcd4621d373cade4e832627b4f6
but I need
return numhash(234); // returns 00978902923102372190
(20 numbers only)
the problem here is that I want the hashing to be short.
edit:
OK let me explain the back story here.
I have a site that has a ID for every registered person, also I need a ID for the person to use and exchange (hence it can't be too long), so far the ID numbering has been 00001, 00002, 00003 etc...
this makes some people look more important
this reveals application info that I don't want to reveal.
To fix point 1 and 2 I need to "hide" the number while keeping it unique.
Edit + SOLUTION:
Numeric hash function based on the code by https://stackoverflow.com/a/23679870/175071
/**
* Return a number only hash
* https://stackoverflow.com/a/23679870/175071
* #param $str
* #param null $len
* #return number
*/
public function numHash($str, $len=null)
{
$binhash = md5($str, true);
$numhash = unpack('N2', $binhash);
$hash = $numhash[1] . $numhash[2];
if($len && is_int($len)) {
$hash = substr($hash, 0, $len);
}
return $hash;
}
// Usage
numHash(234, 20); // always returns 6814430791721596451
An MD5 or SHA1 hash in PHP returns a hexadecimal number, so all you need to do is convert bases. PHP has a function that can do this for you:
$bignum = hexdec( md5("test") );
or
$bignum = hexdec( sha1("test") );
PHP Manual for hexdec
Since you want a limited size number, you could then use modular division to put it in a range you want.
$smallnum = $bignum % [put your upper bound here]
EDIT
As noted by Artefacto in the comments, using this approach will result in a number beyond the maximum size of an Integer in PHP, and the result after modular division will always be 0. However, taking a substring of the hash that contains the first 16 characters doesn't have this problem. Revised version for calculating the initial large number:
$bignum = hexdec( substr(sha1("test"), 0, 15) );
You can try crc32(). See the documentation at: http://php.net/manual/en/function.crc32.php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
printf("%u\n", $checksum); // prints 2191738434
With that said, crc should only be used to validate the integrity of data.
There are some good answers but for me the approaches seem silly.
They first force php to create a Hex number, then convert this back (hexdec) in a BigInteger and then cut it down to a number of letters... this is much work!
Instead why not
Read the hash as binary:
$binhash = md5('[input value]', true);
then using
$numhash = unpack('N2', $binhash); //- or 'V2' for little endian
to cast this as two INTs ($numhash is an array of two elements). Now you can reduce the number of bits in the number simply using an AND operation. e.g:
$result = $numhash[1] & 0x000FFFFF; //- to get numbers between 0 and 1048575
But be warned of collisions! Reducing the number means increasing the probability of two different [input value] with the same output.
I think that the much better way would be the use of "ID-Crypting" with a Bijectiv function. So no collisions could happen! For the simplest kind just use an Affine_cipher
Example with max input value range from 0 to 25:
function numcrypt($a)
{
return ($a * 15) % 26;
}
function unnumcrypt($a)
{
return ($a * 7) % 26;
}
Output:
numcrypt(1) : 15
numcrypt(2) : 4
numcrypt(3) : 19
unnumcrypt(15) : 1
unnumcrypt(4) : 2
unnumcrypt(19) : 3
e.g.
$id = unnumcrypt($_GET('userid'));
... do something with the ID ...
echo ' go ';
of course this is not secure, but if no one knows the method used for your encryption then there are no security reasons then this way is faster and collision safe.
The problem of cut off the hash are the collisions, to avoid it try:
return hexdec(crc32("Hello World"));
The crc32():
Generates the cyclic redundancy checksum polynomial of 32-bit lengths
of the str. This is usually used to validate the integrity of data
being transmitted.
That give us an integer of 32 bit, negative in 32 bits installation, or positive in the 64 bits. This integer could be store like an ID in a database. This don´t have collision problems, because it fits into 32bits variable, once you convert it to decimal with the hexdec() function.
First of all, md5 is basically compromised, so you shouldn't be using it for anything but non-critical hashing.
PHP5 has the hash() function, see http://www.php.net/manual/en/function.hash.php.
Setting the last parameter to true will give you a string of binary data. Alternatively, you could split the resulting hexadecimal hash into pieces of 2 characters and convert them to integers individually, but I'd expect that to be much slower.
Try hashid.
It hash a number into format you can define. The formats include how many character, and what character included.
Example:
$hashids->encode(1);
Will return "28630" depends on your format,
Just use my manual hash method below:
Divide the number (e.g. 6 digit) by prime values, 3,5,7.
And get the first 6 values that are in the decimal places as the ID to be used. Do a check on uniqueness before actual creation of the ID, if a collision exists, increase the last digit by +1 until a non collision.
E.g. 123456 gives you 771428
123457 gives you 780952
123458 gives you 790476.
In PHP I have the following code:
<?PHP
$var = .000021;
echo $var;
?>
the output is 2.1E-5 !
Why? it should print .000021
Use number_format() to get what you're after:
print number_format($var, 5);
Also check sprintf()
2.1E-5 is the same number as 0.000021. That's how it prints numbers below 0.001. Use printf() if you want it in a particular format.
Edit If you're not familiar with the 2.1E-5 syntax, you should know it is shorthand for 2.1×10-5. It is how most programming languages represent numbers in scientific notation.
Use number_format or sprintf if you want to see the number as you expect.
echo sprintf('%f', $var);
echo number_format($var, 6);
To show a number up to 8 decimal spaces, without extra zeroes to the right (as number_format does, which can be annoying), use this:
echo rtrim(rtrim(sprintf('%.8F', $var), '0'), ".");
In general, a number is a number, not a string, and this means that any programming language treats a number as a number. Thus, the number by itself doesn't imply any specific format (like using .000021 instead of 2.1e-5). This is nothing different to displaying a number with leading zeros (like 0.000021) or aligning lists of numbers. This is a general issue you'll find in any programming language: if you want a specific format you need to specify it, using the format functions of your programming language.
Unless you specify the number as string and convert it to a real number when needed, of course. Some languages can do this implicitly.
The previous answers responded to OP question, but none offered the code to do it.
Use this function to format any number with E- format.
function format_amount_with_no_e($amount) {
$amount = (string)$amount; // cast the number in string
$pos = stripos($amount, 'E-'); // get the E- position
$there_is_e = $pos !== false; // E- is found
if ($there_is_e) {
$decimals = intval(substr($amount, $pos + 2, strlen($amount))); // extract the decimals
$amount = number_format($amount, $decimals, '.', ','); // format the number without E-
}
return $amount;
}
Please note the function will always return a string.
Programming languages have different methods for storing numbers in memory. This is determined by the type of number that is being used. In your case, you have a floating point number (a fraction) that is to large to be stored as a fixed point number ( fractions are stored in this manner depending on their size).
This is a very important feature especially when working with very large or very small numbers. For instance, NASA or spaceX uses special storage methods for its calculations to ensure that the rockets the re-enter earths orbit land where they should.
Also, different storage methods take up different amounts of memory. However, the solution provided above should work. Just remember round off errors might occur with very big or small numbers.
When 10000-100, then result should be 9900.
I tried when I use:-
< ?php
$num1 = number_format(round(10000,1),2);
$num2 = number_format(round(100,1),2);
echo $num1 - $num2;
?>
The above result is -90, that made me realize that the number_format function is not applicable in calculations.
Would there be any way that I can convert a value of number_format (obtained from POST from a previous page) back to numerical value for normal calculation?
To start, the reason is that:
(int) "10,000.00"
resolves to 10 since it stops parsing at the first non-numeric character. Thanks to PHP's weird type system, this is done implicitly when you subtract the strings.
Yes, you can strip out the commas easily:
$unformatted = str_replace(",", "", $formatted);
but it's cleaner to just post the raw numeric value (you can still use number_format for the displayed value).
EDIT: It is good practice to explicitly convert numeric strings (without commas) to float (or int) with either a cast ((int) or (float)) or the function version (intval or floatval).
I don't think you can perform this 10,000.00 -100.00 with the comma in the equation. Just perform the raw arithmetic operation then format the answer.
$num1 = 10000;
$num2 = 100;
echo number_format(round($num1 - $num2,1),2);
This outputs
9,900.00
There is an easier way.
number_format is for fomating output numbers or to round easy numbers.
number_format gives us power to make well fomed rounded numbers, for a better user experience.
For calcualtion and saving Numbers in your MYSQL Database use this.
Save your Numbers in MYSQL always as type DECIMAL not FLOAT. There are lots of bugs if you want to calculate with FLOAT fields.
Than use the english notation.
$number = 1234.56;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', ''); //
// 1234.57
And now you can calculate and save it, without any Bugs.
Always Remember yourself, Saving numbers into $var is always a string.
Yeah, you can deifine type, but it doesn't matter in first case, and its to long to explain here.
For more information about number_format see here -> http://php.net/manual/en/function.number-format.php
I have a project where I have to generate random numbers from 00000 till 99999.
The randomizing isn't where I get stuck, but the fact that it always needs 5 characters is. So when it generates the number 14, I want it as 00014.
What is the best way to achieve this?
sprintf() can do that:
echo sprintf('%05d', 0);
Or use str_pad() - but that's a little bit longer in code:
echo str_pad(0, 5, 0, STR_PAD_LEFT);
str_pad() is able to do what you need the code to be done.
Simply:
$s = str_pad('14', 5, '0', STR_PAD_LEFT);
generate integers with leading 0's
An integer will never have leading 0's.
If you need leading 0's you nedd to convert the integer to an string -> see the answer from thephpdeveloper. This is the right way for writing an number with leading 0's into a database - for example.
If you like to work with that integer (for example for calculations) it's better to leave the integer as an integer (don't change to string) and every time you need to output those numbers -> take the solution from "Stefan Gehrig"
Even substr() can do it:
print substr('0000' . $myRandomNumber, -5);
(Not that I would recommend this. Just wanted to contribute :) )
In PHP I have the following code:
<?PHP
$var = .000021;
echo $var;
?>
the output is 2.1E-5 !
Why? it should print .000021
Use number_format() to get what you're after:
print number_format($var, 5);
Also check sprintf()
2.1E-5 is the same number as 0.000021. That's how it prints numbers below 0.001. Use printf() if you want it in a particular format.
Edit If you're not familiar with the 2.1E-5 syntax, you should know it is shorthand for 2.1×10-5. It is how most programming languages represent numbers in scientific notation.
Use number_format or sprintf if you want to see the number as you expect.
echo sprintf('%f', $var);
echo number_format($var, 6);
To show a number up to 8 decimal spaces, without extra zeroes to the right (as number_format does, which can be annoying), use this:
echo rtrim(rtrim(sprintf('%.8F', $var), '0'), ".");
In general, a number is a number, not a string, and this means that any programming language treats a number as a number. Thus, the number by itself doesn't imply any specific format (like using .000021 instead of 2.1e-5). This is nothing different to displaying a number with leading zeros (like 0.000021) or aligning lists of numbers. This is a general issue you'll find in any programming language: if you want a specific format you need to specify it, using the format functions of your programming language.
Unless you specify the number as string and convert it to a real number when needed, of course. Some languages can do this implicitly.
The previous answers responded to OP question, but none offered the code to do it.
Use this function to format any number with E- format.
function format_amount_with_no_e($amount) {
$amount = (string)$amount; // cast the number in string
$pos = stripos($amount, 'E-'); // get the E- position
$there_is_e = $pos !== false; // E- is found
if ($there_is_e) {
$decimals = intval(substr($amount, $pos + 2, strlen($amount))); // extract the decimals
$amount = number_format($amount, $decimals, '.', ','); // format the number without E-
}
return $amount;
}
Please note the function will always return a string.
Programming languages have different methods for storing numbers in memory. This is determined by the type of number that is being used. In your case, you have a floating point number (a fraction) that is to large to be stored as a fixed point number ( fractions are stored in this manner depending on their size).
This is a very important feature especially when working with very large or very small numbers. For instance, NASA or spaceX uses special storage methods for its calculations to ensure that the rockets the re-enter earths orbit land where they should.
Also, different storage methods take up different amounts of memory. However, the solution provided above should work. Just remember round off errors might occur with very big or small numbers.