0

I want to format a Double obtained from an Object so it only displays three digits after the decimal point. Here's the current code:

 Three a = Data.get(index); 
 // Get the y-axis acceleration value
 double b = a.getY();
 String accelerationOutUnfiltered = Double.toString(b);
 Data[0] = accelerationOutUnfiltered;

Note: I am doing this in Android, and when I use String.format("%.3f", y) this doesn't work and it throws me a error in Android Studio. Currently the above code works but it displays 15 digits after the decimal point.

I have tried several forms, but they all have failed. Please help. Thanks :)

earthw0rmjim
  • 17,394
  • 8
  • 45
  • 61
jlopez
  • 67
  • 5

2 Answers2

1

You could use DecimalFormatter.

For example:

double b = a.getY();

DecimalFormat formatter = new DecimalFormat("#.###");
formatter.setRoundingMode(RoundingMode.CEILING);

String formattedDouble = formatter.format(b);
earthw0rmjim
  • 17,394
  • 8
  • 45
  • 61
  • That worked. Thank you. Now, I need to do it for formatting three values to write them in a file. I tried: String a= formatter2.format(g, h, i); But it doesn't work. – jlopez Jul 16 '16 at 17:45
  • Format the values separately, and then concatenate them into one `String`. – earthw0rmjim Jul 16 '16 at 17:51
0

Have tried decimal formatter?

You do something like this:

DecimalFormat df = new DecimalFormat("#.#####");
df.format(<your_number>);
akortex91
  • 3,290
  • 2
  • 13
  • 31