Languages
[Edit]
EN

Java - get random float number

12 points
Created by:
JustMike
3488

1. Generate random float with ThreadLocalRandom class

public static float nextFloat() {
    return ThreadLocalRandom.current().nextFloat();
}

Example:

System.out.println(nextFloat()); // 0.5261965
System.out.println(nextFloat()); // 0.23931652
System.out.println(nextFloat()); // 0.8099988


2. Generate random float with Random class

public static float nextFloat2() {
    return new Random().nextFloat();
}

Example:

System.out.println(nextFloat2()); // 0.0030902028
System.out.println(nextFloat2()); // 0.77623594
System.out.println(nextFloat2()); // 0.39141566


References

ThreadLocalRandom - Java docs
Random - Java docs

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.