Format Float to n Decimal Places with String Format
To format a float to a specified number of decimal places, consider using the String.format() method instead of BigDecimal:
<code class="java">import java.lang.Math; public static float Redondear(float pNumero, int pCantidadDecimales) { //Round the float value and convert it to a string with specified decimal places String roundedValue = String.format("%.2f", pNumero); //Parse the string back to a float to maintain float precision return Float.parseFloat(roundedValue); }</code>
Example:
<code class="java">float originalValue = 625.3f; int decimalPlaces = 2; float roundedValue = Redondear(originalValue, decimalPlaces); System.out.println("Rounded Value: " + roundedValue); // Output: 625.30</code>
Documentation:
The above is the detailed content of How to Format a Float to N Decimal Places in Java?. For more information, please follow other related articles on the PHP Chinese website!