user461579
user461579

Reputation: 21

Java rounding Issue

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.

Upvotes: 2

Views: 229

Answers (2)

Qwerky
Qwerky

Reputation: 18445

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);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500625

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);
  }
}

Upvotes: 2

Related Questions