7

I am trying to make a program that takes some user input, runs a few calculations and outputs the answer. My problem is that this answer is sometimes many decimal places long which is causing some aesthetic and layout problems. I only need to display 4 decimal places worth of data. Is there anyway to limit the precision of these numbers at output time? (The Numbers are stored in floats and I'm programming for Android.)

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Tom C
  • 232
  • 1
  • 6
  • 17

1 Answers1

30

You can format a float to 4 decimal places using String.format.

Example:

String result = String.format("%.4f", theNumber);

See also:

Community
  • 1
  • 1
Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118