0

So let's say I have a simple array of float numbers

[0.315023, 1.0, 0.12345, 0121111]

And call it arr1.

I need to take this array and turn it into this:

[0.3150, 1.0000, 0.1234, 0.1211] *Please note that 1.0 is now 1.0000 and 0.3150 has a 0 at the end

I have tried using a for loop to iterate through the array and rounding the numbers as follows:

// i representing a number in the arr1; let's imagine that "newNum" replace the original numbers in arr1 float newNum = Math.round(i*10000.0000)/10000.0000;

What will result is following:

[0.315, 1.0, 0.1234, 0.1211]

As you can see, the first item is missing the 0 at the end, and the second item is missing a lot of zeros at the end.

I have tried to use DecimalFormat, but it doesn't work with the float array; also I am not trying to format decimals, I am rounding them. (although I have tried the round first then format second; which didn't work because of difference in datatype).

PLEASE for the love of God, help me. This is like the last thing I need to complete for my project. I am so close! Thank you so much in advance!

*PS: I need to make sure the array remains FLOAT; I need to use the data in the array later on.

Y. Nam
  • 1
  • 2
  • Do with `BigDecimal`. Set scale upto 4. – bNd Jan 27 '16 at 06:25
  • What is the type of your final array? Float? – Ian Jan 27 '16 at 06:28
  • 2
    https://docs.oracle.com/javase/tutorial/java/data/numberformat.html. Your question is not about "how to round", but rather "how to format". – ajb Jan 27 '16 at 06:29
  • `System.out.printf("%.4f %.4f %.4f %.4f%n", 0.315023, 1.0, 0.12345, 0.121111)` will print `0.3150 1.0000 0.1235 0.1211`. – Andreas Jan 27 '16 at 06:35

2 Answers2

0

Use this:-

 DecimalFormat twoDForm = new DecimalFormat("#.####");
 double d = Double.valueOf(twoDForm.format(newNum));
Md Mahfuzur Rahman
  • 2,319
  • 2
  • 18
  • 28
0
DecimalFormat f = new DecimalFormat("##.0000");
  System.out.println(" output : "+ f.format(2.56));

Follows java docs for format data

Rahul Bhawar
  • 450
  • 7
  • 17