2

I have this code below, my desired answer is 37.58 and not 37.56 or 37.60 after inputting 37576

BigDecimal n = new BigDecimal(num);
BigDecimal t = new BigDecimal(100);

BigDecimal res = n.divide(t);
BigDecimal b =res.setScale(1, BigDecimal.ROUND_HALF_UP);
DecimalFormat forma = new DecimalFormat("K0.00");
String bigf = forma.format(b);



txtnewk.setText(" " + bigf);

what changes do I have to make?

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
Brianmuks
  • 49
  • 7

4 Answers4

3

With the following code:

String num = "37576";
BigDecimal n = new BigDecimal(num);
BigDecimal t = new BigDecimal(1000);
BigDecimal res = n.divide(t);
BigDecimal b = res.setScale(2, BigDecimal.ROUND_HALF_UP);

b is 37.58 as desired.

assylias
  • 321,522
  • 82
  • 660
  • 783
0

Use this code for rounding numbers:

public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}
Community
  • 1
  • 1
ObAt
  • 2,337
  • 3
  • 24
  • 44
0

You are using wrong version of divide (if you are rounding it immediately). Value of setScale is wrong. You should have:

BigDecimal res = n.divide(t, 2, BigDecimal.ROUND_HALF_UP);
Marek R
  • 32,568
  • 6
  • 55
  • 140
0

Using double you can do

long l = 37576; // or Long.parseLong(text);
double v = Math.round(l / 10.0) / 100.0;
System.out.println(v);

prints

37.58

The first rounded / 10.0 says you want to drop the lowest digit by rounding and the / 100.0 says you want to shift the decimal place by two digits.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130