In Java, I need to randomly generate a number between 0
and 0.06
.
I saw on another question on here that the following code would do the trick:
Random generator = new Random();
double number = generator.nextDouble() * .06;
However, doing that gives me really long numbers like 0.007044013589130205
and 0.03656588431980957
, which I don't think is what my instructor is looking for.
Is there anyway to generate random numbers between 0 and 0.06 that only have two or three decimal places?
You can do it this way, if you want you number to range between [0;0.06] with 0.01 of difference:
Random generator = new Random();
int number = generator.nextInt(7);
double result = number / 100.0;
You can generalize the formula number = generator.nextInt(max + 1 -min) + min;
where max will be the biggest number that you what to generate and min the lowest. This will generate number from [min to max+1]
To increase the decimal places you just have to divide number for 1000, 10000 and so on.
Internally, Java double
values are a binary floating point representation. They don't have decimal places. You can format a double as a base-10 number string having a specified number of decimal places. For example, to get three decimals (precision 0.001), you could use:
String formatted = String.format("%.3f", number);
If you don't need to do any calculations with the number and you want two or three decimal places, just print 0.0
and then a two-digit random integer between 00 and 60 (inclusive).
I assume you need precision to be 0.001, so try this:
Random r = new Random();
int ret = r.nextInt(60 + 1);
return ret / 1000.0;
this will generate [0,0.060] averagely with difference multiple of 0.001,that may be your want
Since you're dealing with sales tax, you should be aware of Why not use Double or Float to represent currency? and Using BigDecimal to work with currencies
To generate a random BigDecimal
with constraints on range and # of significant digits, see How can I create a random BigDecimal in Java?