29. Rounding a float number to specified decimals
Consider the following float number and the number of decimals that we want to keep:
float v = 14.9877655f;
int d = 5;
So the expected result after rounding up is 14.98777.
We can solve this problem in a straightforward manner in at least three ways. For instance, we can rely on the BigDecimal API, as follows:
public static float roundToDecimals(float v, int decimals) {
BigDecimal bd = new BigDecimal(Float.toString(v));
bd = bd.setScale(decimals, RoundingMode.HALF_UP);
return bd.floatValue();
}
First, we create a BigDecimal number from the given float. Second, we scale this BigDecimal to the desired number of decimals. Finally, we return the new float value.
Another approach can rely on DecimalFormat, as follows:
public static float roundToDecimals(float v, int decimals) {
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(decimals);
return Float.parseFloat(df.format(v));
...