Reputation: 113
x = rd.nextInt((4000) - 2000) / 1000.0;
This is generating numbers between [0, 2] to the thousandth decimal which is what I want, I just also need negative number so the range of numbers generated is between [-2, 2].
Upvotes: 7
Views: 1132
Reputation: 424983
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:
Upvotes: 5
Reputation: 446
You can generate random number on a range [0,4] and then simply subtract 2 from the result:
x = (rd.nextInt(4000) / 1000.0) - 2;
Upvotes: -1
Reputation: 567
You can generate a random float and then use a modulo to truncate it to the hundredth decimal place.
int min = -2;
int max = 2;
Random rand = new Random();
float ret = rand.nextFloat() * (max - min) + min;
return ret - (ret % 0.01);
Upvotes: 1
Reputation: 201429
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);
Upvotes: 2