0

I'm doing a calculation on android studio (java) and the answer that I get back is like 4.654783632444251. I don't want the long answers. Preferably Two Decimal places would be ideal. Using Double.parseDouble

Corey
  • 35
  • 9

2 Answers2

1

You can round it to two decimal places:

Math.round(myNumber * 100) / 100

Or you can format it using

String.format("%.2f", myNumber)

The second method even prints the decimal places if they are 0.

Aloso
  • 5,123
  • 4
  • 24
  • 41
0
protected double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}

Just call this method entering your value and 2 places.

Eclipse
  • 175
  • 1
  • 12