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?
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?You can do it this way, if you want you number to range between [0;0.06] with 0.01 of difference:
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.
I assume you need precision to be 0.001, so try this:
this will generate [0,0.060] averagely with difference multiple of 0.001,that may be your want
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: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).