Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float Precision Display (Android)

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.)

like image 572
Tom C Avatar asked Jan 23 '11 13:01

Tom C


1 Answers

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

Example:

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

See also:

  • How to nicely format floating numbers to String without unnecessary decimal 0?
  • String.format(format, args)
  • Format strings in Java
like image 163
Sebastian Paaske Tørholm Avatar answered Oct 21 '22 05:10

Sebastian Paaske Tørholm