I have a case, such that, if the float value 开发者_C百科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.
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);
  }
}
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);
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论