Alireza Jalilii Alireza Jalilii - 7 days ago 5
Java Question

Generate a Random Double With Specific 6 Digit decimal

I want to create a Random Double with 6 decimal digits precision, buts this code doesnt do this always :/ Where is the problem of this code?

double random = Double.parseDouble(String.format("%.6f", new Random().nextDouble()));
double SP = 0.0 + (random * (7.0 - 0.0));


here is the random number that has been generated by this code for 10 times:


  • 6.321637

  • 6.971019999999996

  • 0.763686

  • 0.14724500000000001

  • 0.240456

  • 3.268468

  • 2.112775

  • 2.5137419999999997

  • 4.637668

  • 4.712155



Here is Full code With Correction that @javaguy Answered .
And Now It Works: (But Attention To Change 'StartNumber' And 'EndNumber' like this : 2.5 )

import java.util.Random;
double random = new Random().nextDouble();
double N = SartNumber + (random * (EndNumber - StartNumber));
N = Double.parseDouble(String.format("%.6f", N)); //N Is Your Number

Answer

You are multiplying with double after formatting, so you are loosing your previous format, so change your code as shown below which does the formatting at the end, once after all calculations are done:

double random = new Random().nextDouble(); 
double SP = 0.0 + (random * (7.0 - 0.0)); 
SP = Double.parseDouble(String.format("%.6f", SP)); //now do format
Comments