0

I'm trying to set random values to an array using Math.Random(), but it is printing values with 15 decimal places when I only want 2. How do I fix this?

This is what I have so far it works and gives me values like:

[9.410800457889598, 7.816378845915057, 7.4315520333161995, 7.4844070010512285, 7.6640924183174945].

public static void populateArray(double[] judge){
    for(int n=0;n<=4;n++){
        double score =(Math.random()*(3)+7);
        judge[n] = score;
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • Use the `Random` `nextInt` method to get values between 1 and 999 and multiply the result by 0.01. – Gilbert Le Blanc Mar 21 '22 at 07:52
  • Double itself has nothing to do with that, it doesnt even have a concept of decimal places itself. It is rather the process of converting the double to a String (when you print it), where this stuff gets introduced. You have to use a formatter at this point to tell it that you want Strings with two places instead. – Zabuzard Mar 21 '22 at 07:53
  • 1
    @GilbertLeBlanc That can still give you stuff like `5.1200000000000000000001`. There isnt really a way around using formatters. – Zabuzard Mar 21 '22 at 07:54
  • 1
    @Zabuzard: Yes, you have to use a formatter. I was addressing the random distribution problem created by just formatting the random result. – Gilbert Le Blanc Mar 21 '22 at 07:58

0 Answers0