Hi, I have this method done in Java and the result it returns is a number with many decimal places, I would like some way to return only two decimal places.
Code:
public static float calcularMedia(int[] notas)
{
float resultado = 0;
for(int nota: notas)
{
resultado+=nota;
}
return resultado/notas.length;
}
You can use this function that always returns all the numbers that have decimals with the format that you pass to it, but omits decimals for the numbers that do not:
If it's about printing to console, you can use
System.out.printf
orString.format
. ExampleUsing
System.out.printf
:Using
String.format
:This will round to two decimal places:
To three decimals: