php random float – How to generate a random float number in php?

php random float – you can use rand() function for that in php. Write a PHP function to get random float numbers. Create a function to generate a random float number.

php random float

Random float number between 0 and 1.0 php

Example

mt_rand() / mt_getrandmax();

$randomFloat = rand(0, 10) / 10;
var_dump($randomFloat);

//eg. float(0.7)

Random floating-point values from 0 to 10 with two decimals :

<?php
function frand($min, $max, $decimals = 0) {
  $scale = pow(10, $decimals);
  return mt_rand($min * $scale, $max * $scale) / $scale;
}

echo "frand(0, 10, 2) = " . frand(0, 10, 2) . "\n";
?>

How to generate a random float number in php?

Create a function to generate a random float number using this code:
Example

function getrd_flt_value($first_no = 0,$last_no = 1,$mul = 1000000)
{
	if ($first_no > $last_no) return false;
	return mt_rand($first_no * $mul,$last_no * $mul)/$mul;
}

Generate and show random float number


Generate and show random float number using this code:

echo getrd_flt_value().”<br>”;

echo getrd_flt_value(0.6).”<br>”;

echo getrd_flt_value(0.5,0.6).”<br>”;

echo getrd_flt_value(0,20).”<br>”;

echo getrd_flt_value(0,3,2).”<br>”;

echo getrd_flt_value(0,2,20).”<br>”;

PHP generate random alphanumeric string

Read Also:  how to set session in codeigniter?

Complete code to generate a random float number in PHP:

<?php

function getrd_flt_value($first_no = 0,$last_no = 1,$mul = 1000000)
{
  
	if ($first_no > $last_no) return false;

	return mt_rand($first_no * $mul,$last_no * $mul)/$mul;
}

echo getrd_flt_value()."<br>";

echo getrd_flt_value(0.6)."<br>";

echo getrd_flt_value(0.5,0.6)."<br>";

echo getrd_flt_value(0,20)."<br>";

echo getrd_flt_value(0,3,2)."<br>";

echo getrd_flt_value(0,2,20)."<br>";
?>

I hope you get an idea about php random float.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.