What's the best practice to round a float to 2 decimals? [duplicate]
I'm using eclipse + Android SDK.
I need to round a float value to 2 decimals. I usually use the next "trick" using Math library.
float accelerometerX = accelerometerX * 100;
accelerometerX = round(accelerometerX);
Log.d("Test","" + accelerometerX/100);
But I feel it is not the best way to do it.
Is there a library to do these type of operations?
Solution 1:
I was working with statistics in Java 2 years ago and I still got the codes of a function that allows you to round a number to the number of decimals that you want. Now you need two, but maybe you would like to try with 3 to compare results, and this function gives you this freedom.
/**
* Round to certain number of decimals
*
* @param d
* @param decimalPlace
* @return
*/
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 if you want to round up or down. In my sample code I am rounding up.
Hope it helps.
EDIT
If you want to preserve the number of decimals when they are zero (I guess it is just for displaying to the user) you just have to change the function type from float to BigDecimal, like this:
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 this way:
float x = 2.3f;
BigDecimal result;
result=round(x,2);
System.out.println(result);
This will print:
2.30
Solution 2:
Let's test 3 methods:
1)
public static double round1(double value, int scale) {
return Math.round(value * Math.pow(10, scale)) / Math.pow(10, scale);
}
2)
public static float round2(float number, int scale) {
int pow = 10;
for (int i = 1; i < scale; i++)
pow *= 10;
float tmp = number * pow;
return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}
3)
public static float round3(float d, int decimalPlace) {
return BigDecimal.valueOf(d).setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).floatValue();
}
Number is 0.23453f
We'll test 100,000 iterations each method.
Results:
Time 1 - 18 ms
Time 2 - 1 ms
Time 3 - 378 ms
Tested on laptop
Intel i3-3310M CPU 2.4GHz
Solution 3:
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
Solution 4:
Here is a shorter implementation comparing to @Jav_Rock's
/**
* Round to certain number of decimals
*
* @param d
* @param decimalPlace the numbers of decimals
* @return
*/
public static float round(float d, int decimalPlace) {
return BigDecimal.valueOf(d).setScale(decimalPlace,BigDecimal.ROUND_HALF_UP).floatValue();
}
System.out.println(round(2.345f,2));//two decimal digits, //2.35