Format Float to n decimal places

seba123neo picture seba123neo · Mar 4, 2011 · Viewed 352.3k times · Source

I need to format a float to "n"decimal places.

was trying to BigDecimal, but the return value is not correct...

public static float Redondear(float pNumero, int pCantidadDecimales) {
    // the function is call with the values Redondear(625.3f, 2)
    BigDecimal value = new BigDecimal(pNumero);
    value = value.setScale(pCantidadDecimales, RoundingMode.HALF_EVEN); // here the value is correct (625.30)
    return value.floatValue(); // but here the values is 625.3
}

I need to return a float value with the number of decimal places that I specify.

I need Float value return not Double

.

Answer

Arve picture Arve · Mar 21, 2011

You may also pass the float value, and use:

String.format("%.2f", floatValue);

Documentation