0

Having a lot of trouble rounding a value to display in a textView.

I basically wanna round it to two decimal places but at the moment I am getting a long trail of different numbers.

I am playing around with BigDecimal but no luck so far...

public void calc() {
        BigDecimal bd = new BigDecimal(subTotal);
        bd.setScale(2, BigDecimal.ROUND_DOWN);
        total.setText(String.valueOf(bd));
    }
Terel
  • 3,857
  • 1
  • 25
  • 28
Javacadabra
  • 5,578
  • 15
  • 84
  • 152
  • 1
    Don't use floating-point values to represent currency! See http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – Graham Borland Dec 12 '12 at 00:04

2 Answers2

1

Try the following code:

double roundTwoDecimals(double d) {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}
Squonk
  • 48,735
  • 19
  • 103
  • 135
Pavlos
  • 2,183
  • 2
  • 20
  • 27
0

Following worked for me

BigDecimal bd = new BigDecimal(subTotal);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
total.setText(String.valueOf(bd));
// Input: 9.888888 -> Output: 9.89
// Input: 9f -> Output: 9.00
Terel
  • 3,857
  • 1
  • 25
  • 28