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

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

Susan Sarandon
Release: 2024-11-01 13:38:02
Original
709 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template