2

I have a case, such that, if the float value is 74.126, it is rounded into 74.13 ie. into 2 decimal places. But if the value is 74.125, it should be rounded into 74.12...

Please help me to achieve this kind of rounding methodology

Thanks in advance.

user461579
  • 21
  • 1
  • It's standard math to round up when x.5 and round down when < x.5 – halfdan Sep 29 '10 at 09:58
  • possible duplicate of [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – Greg Hewgill Sep 29 '10 at 10:02

2 Answers2

2

I suggest you use BigDecimal instead of float, as that's a more natural representation where decimal digits make sense.

However, I don't think you actually want the round method, as that deals with precision instead of scale. I think you want setScale, as demonstrated here:

import java.math.*;
public class Test {
  public static void main(String[] args) {
    roundTo2DP("74.126");
    roundTo2DP("74.125");
  }

  private static void roundTo2DP(String text) {
    BigDecimal before = new BigDecimal(text);
    BigDecimal after = before.setScale(2, RoundingMode.HALF_DOWN);
    System.out.println(after);
  }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Presumably you are rounding with Math.round(float a)? If so the javadocs explain pretty much how rounding works better than I can here.

You may want to look at the BigDecimal class as it provides a round(MathContext mc) method that allows you to specify different rounding modes such as HALF_DOWN.

Edit: If you just want to set the number of decimal places you can do it with the setScale method.

float f = 74.125f;
BigDecimal b = new BigDecimal(f).setScale(2, RoundingMode.HALF_DOWN);
Qwerky
  • 18,217
  • 6
  • 44
  • 80