Reputation: 3
public class Main {
public static void main(String[] args) {
generateRandomNumber();
}
public static void generateRandomNumber(){
double[] insideArray = new double[5];
for(int i=0; i<insideArray.length; i++) {
double value = (Math.random()+1)*10;
insideArray[i] = value;
String.format("%.2f", insideArray[i]);
}
System.out.println("Displaying random generated Array: " + Arrays.toString(insideArray));
}
}
I am trying to generate 5 random numbers and store to an Array. And I would like to format decimals up to 2 numbers. I tried "String.format()" method but didn't work. Still I am getting double like: 10.xxxxxxxxxxx.
How can I format it such as ex: 10.xx ?
Upvotes: 0
Views: 70
Reputation: 1051
When you print a double varible it can't be always limit to 2 decimal digits. Either use BigDecimal or store it in the form of string.
public static void generateRandomNumber(){
String [] insideArray = new String[5]; // double array to string array
for(int i=0; i<insideArray.length; i++) {
double value = (Math.random()+1)*10;
insideArray[i] = String.format("%.2f", value); // store the converted number in the form of string.
}
System.out.println("Displaying random generated Array: " + Arrays.toString(insideArray));
}
Upvotes: 0
Reputation: 3691
String.format(String, double);
returns the formated String. It doesn't change the object you want to format.
In other words: insideArray[i]
is still an unrounded double after calling String.format
.
The easiest way to solve your issue would be to store the result of String.format
inside the array. But the result is a String
and the array is a double
array. Those type don't match.
You can either declare a second array to store the strings, or simply change the type of insideArray
, as it seems you don't do anything further with its elements.
Solution A:
double[] insideArray = new double[5];
String[] myStringArray = new String[5];
for(int i=0; i<insideArray.length; i++) {
double value = (Math.random()+1)*10;
insideArray[i] = value;
myStringArray[i] = String.format("%.2f", insideArray[i]);
}
System.out.println("Displaying random generated Array: " + Arrays.toString(myStringArray));
Solution B:
String[] insideArray = new String[5];
for(int i=0; i<insideArray.length; i++) {
double value = (Math.random()+1)*10;
insideArray[i] =String.format("%.2f", value);
}
System.out.println("Displaying random generated Array: " + Arrays.toString(insideArray));
Upvotes: 2