Generate Random X.XXX numbers between [-2, 2]

The problem you are facing is integer arithmetic, which truncates the fractional part of the result. Use rd.nextDouble() instead so the arithmetic results are double, which retains the fractional part.

However, to round to 1/100ths, you can use integer arthmetic to your advantage.

Your question has the text to the hundredth decimal, so here's that solution:

x = (int)(((rd.nextDouble() * 4) - 2) * 100) / 100d;

But your title mentions X.XXX, so here's that solution:

x = (int)(((rd.nextDouble() * 4) - 2) * 1000) / 1000d;

To unravel what's going on here:

  1. generate random double between 0.000000 and 1.000000
  2. multiply by the scale of the range, so we get a number between 0.000000 and 4.000000
  3. subtract 2, so we get a number between -2.000000 and 2.000000
  4. multiply by 1000, so we get a number between -2000.000000 and 2000.000000
  5. cast to int to truncate the fraction, so we get a int between -2000 and 2000
  6. divide by 1000d (which is a double), so we get a double between -2.000 and 2.000

Floating point numbers do not always have a precise number of digits. Also, the third decimal place is called thousandths (the hundredth decimal would be the second digit after the .). I think you know this because you are dividing by a thousand. So, step one: generate a single random value between 0 and 4 as a double. Step two: Subtract two and convert to a formatted String (so you can control the number of digits).

double d = (rd.nextDouble() * 4) - 2;
String x = String.format("%.3f", d);

Tags:

Java