Home  >  Article  >  Java  >  How to Format a Float to N Decimal Places in Java?

How to Format a Float to N Decimal Places in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 13:38:02562browse

How to Format a Float to N Decimal Places in Java?

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:

  • [String.format()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String, java.lang.Object...))

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn