I worked with statistics in Java 2 years ago, and I still have function codes that allows you to round a number to the number of decimal places you want. Now you need two, but maybe you should try to compare the results with 3, and this function gives you this freedom.
public static float round(float d, int decimalPlace) { BigDecimal bd = new BigDecimal(Float.toString(d)); bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP); return bd.floatValue(); }
You need to decide whether you want to round up or down. In my code example, I round.
Hope this helps.
EDIT
If you want to keep the number of decimal places when they are zero (I think this is just for display to the user), you just need to change the function type from float to BigDecimal, for example:
public static BigDecimal round(float d, int decimalPlace) { BigDecimal bd = new BigDecimal(Float.toString(d)); bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP); return bd; }
And then call the function as follows:
float x = 2.3f; BigDecimal result; result=round(x,2); System.out.println(result);
This will print:
2.30
Jav_Rock Jan 18 2018-12-18T00: 00Z
source share