Reputation: 125
I have a 2D array of doubles that have been calculated from other doubles. I want the doubles that are stored in the 2D array to be formatted so that they are to 4 decimal places. for example I have an array of:
fragmentMases = [363.076328934] [668.128613182] [974.16124702] [1303.232096646]
[283.109998526] [588.162282774] [894.194916612] [1223.265766238]
[1398.2454009859998] [1053.1796367379998] [748.1273524899999] [442.0947186519999]
[1285.22153196] [940.1557677119999] [635.103483464] [329.070849626]
But I want it to be:
fragmentMases = [363.0763] [668.1286] [974.1612] [1303.2320]
[283.1099] [588.1622] [894.1949] [1223.2657]
[1398.2454] [1053.1796] [748.1273] [442.0947]
[1285.2215] [940.1557] [635.1034] [329.0708]
I have made a function that I thought would do it but it doesn't seem to save it inside the array:
public static void formatArray(double[][] array) {
Formatter fmt = new Formatter();
for(int i = 0; i < 4; i++){
for(int y = 0; y < array.length; y++){
String.valueOf(array).length();
fmt.format("%.4f", array[i][y]);
}
}
}
EDIT
So I run the following:
formatArray(fragmentMasses);
After running this I print out the array and none of the doubles are formatted.
Could anyone help me get this to work and save the formatted 2D array?
Thanks
Upvotes: 1
Views: 1722
Reputation: 2238
You can create new array and override yours with it:
public static double[][] formatArray(double[][] array) {
double[][] newArray = new double[array.length][array[0].length];
for(int i = 0; i < array.length; i++){
for(int y = 0; y < array[0].length; y++){
newArray[i][y] = (double)Math.round(array[i][y] * 10000) / 10000;
}
}
return newArray;
}
or you can change your own array:
public static void formatArray(double[][] array) {
for(int i = 0; i < array.length; i++){
for(int y = 0; y < array[0].length; y++){
array[i][y] = (double)Math.round(array[i][y] * 10000) / 10000;
}
}
}
Upvotes: 2