Generating float numbers with the Randomizer PHP class
Published on 2024-10-05 • Modified on 2024-10-05
This snippet shows how to generate float numbers with the Randomizer PHP class. The $min
and $max
boundaries can be inclusive or not, thanks to the third parameter of the getFloat()
function, which accepts a value from the \Random\IntervalBoundary
enumeration.
<?php
declare(strict_types=1);
namespace App\Controller\Snippet;
use Random\IntervalBoundary;
use Random\Randomizer;
/**
* I am using a PHP trait to isolate each snippet in a file.
* This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
* or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
* Services are injected in the main controller constructor.
*/
trait Snippet322Trait
{
public function snippet322(): void
{
$rnd = new Randomizer();
$float1 = $rnd->nextFloat();
$float2 = $rnd->getFloat(0.5, 5.5);
$float3 = $rnd->getFloat(0.1, 0.2, IntervalBoundary::ClosedClosed); // 0.1 and 0.2 are excluded
echo '[0.0, 1.0): '.$float1.' ('.\strlen((string) $float1).')'.PHP_EOL; // Outputs a float in [0.0, 1.0)
echo '[0.5, 5.5): '.$float2.' ('.\strlen((string) $float2).')'.PHP_EOL; // Outputs a float in [0.5, 2.5)
echo '(0.1, 0.2): '.$float3.' ('.\strlen((string) $float3).')'; // Outputs a float in (0.1, 0.2)
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Read the doc More on the web Random snippet
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉
