Round 2 decimals in Java

0

Good, I have this method done in Java and the result that returns is a number with many decimals, I would like some way for me to return two decimals only.

Code:

public static float calcularMedia(int[] notas)
    {
        float resultado = 0;

        for(int nota: notas)
        {
            resultado+=nota;
        }
        return resultado/notas.length;      
    }   
    
asked by Mario Guiber 28.08.2017 в 12:56
source

2 answers

3

You can use this function that always returns all the numbers that have decimals with the format you pass, but omits decimals for the numbers that do not have:

DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
for (int nota : notas) {
    Double d = nota.doubleValue();
    System.out.println(df.format(d));
}
    
answered by 28.08.2017 / 13:02
source
3

If it's about printing in the console, you can use System.out.printf or String.format . Example

Using System.out.printf :

float f = 12.34567f;
System.out.printf("El número redondeado: %.2f\n", f);

Using String.format :

float f = 12.34567f;
System.out.println(
    String.format("El número redondeado: %.2f", f)
);
    
answered by 28.08.2017 в 19:06