0

My Android app (Java code) is displaying for example 15.0 and the format that I need to display is 15.00. My variable is double. How can I achieve that? What I have tried is the following code from Jonik's answer at Round a double to 2 decimal places:

public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();
    BigDecimal bd = BigDecimal.valueOf(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}

Then I use this:

double myValue = 15.0;
round(myValue, 2);
System.out.println(myValue);

I wanted to see 15.00 printed out. However, what I see is 15.0 and that is not what I want. Any ideas to achieve what I need? Thank you.

Jaime Montoya
  • 6,915
  • 14
  • 67
  • 103

1 Answers1

1

I think you're looking for NumberFormat. Something like this should work:

double a = 10.19823493;
double b = 1.2;

NumberFormat formatter = NumberFormat.getInstance();
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);

System.out.println(formatter.format(a)); // "10.20"
System.out.println(formatter.format(b)); // "1.20"
kingkupps
  • 3,284
  • 2
  • 16
  • 28