0

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
  • 1
    Java double rounding error? http://stackoverflow.com/questions/179427/how-to-resolve-a-java-rounding-double-issue – Peter Gordon Nov 26 '16 at 12:32
  • This is not an error, this is because of the precision a double can get is not accurate for all numbers, you can look into BigDecimal. – Alexandre Lavoie Nov 26 '16 at 12:34
  • The problem is in Double precision. See [this question on SO](http://stackoverflow.com/questions/10786587/java-double-precision-sum-trouble) for more details on this. I recommend you use formatting when printing results to achieve required amount of digits. – Maxim Logunov Nov 26 '16 at 12:36

1 Answers1

2

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
Vasu
  • 21,832
  • 11
  • 51
  • 67