问题
I am trying to get a random double returned to me in the format #.# however I am getting a value of something to this effect: 0.9395772067578356
How do you force only a one decimal return on a random double as I cannot put paraments in the .nextDouble.
myRandomNumGenerator = new Random();
loadedValue = myRandomNumGenerator.nextDouble();
回答1:
DecimalFormat oneDigit = new DecimalFormat("#,##0.0");//format to 1 decimal place
System.out.println(oneDigit.format(anyVariable)); //generic usage
loadedValue = Double.valueOf(oneDigit.format(loadedValue));//specific usage posted in comments
回答2:
I don't think you can force a one place return. You can just make it print the one place, however.
System.out.printf("%.1f", loadedValue);
That will print the value to one place.
来源:https://stackoverflow.com/questions/15193739/how-do-i-round-a-double-to-one-decimal-place