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.

2

2 Answers 2

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.