-2

I create a static class named Box, and there I calculate the parameter double AverageWeight.

Then, in my MainActivity, I would like to print the result in a TextView, and show only two digit after decimal. How do I do that?

I've searched this question on Stack Overflow but I haven't found anything that referred to formatting Double class, and nothing I've tried worked.

//Convert the output from double to String
String avgWeight = Double.toString(Box.getAverageWeight());

//Set the String output to TextView
tv_resAvgWeight.setText(avgWeight);
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
shir k
  • 107
  • 6

1 Answers1

2

You can use Java DecimalFormat class, for example:

DecimalFormat format = new DecimalFormat("#.##");
double d = 1.234242424;
System.out.println(format.format(d));

You can read the full documentation of the class for all the options that are available.

The Coding Monk
  • 7,684
  • 12
  • 41
  • 56