2

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();
Benjiman
  • 420
  • 2
  • 9
Bob
  • 746
  • 3
  • 11
  • 26

2 Answers2

7
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
Benjiman
  • 420
  • 2
  • 9
  • had to add `loadedValue = Double.valueOf(oneDigit.format(loadedValue));` for comparison purposes, but it did the trick. Thanks. – Bob Mar 04 '13 at 02:57
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.

Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
Human Flotsam
  • 33
  • 1
  • 2
  • 6