Format result of integer division

2

I have the following code in JAVA:

private int metros = 1500, minutos = 60;

    System.out.println("Distância em km = "+(metros/1000));

    System.out.println("Tempo em horas = "+(minutoa/60));

However what is displayed after the execution of this is 1km and I wanted it to print on the screen the value formatted ex: "1.5 km" without the need to create a double variable, that is, if it is possible.

This same problem applies to hours, for example, when people to split 90 min it should return me 1 and 30 min from the leftovers, instead it returns me 1 hour.

    
asked by anonymous 31.12.2016 / 12:00

2 answers

9

A simple and straightforward solution would simply be to add a% float to one of the operands:

System.out.println("Distância em km = "+(metros/1000f));

and for hours, just get the hours dividing by 60 and the minutes picking up the division module by 60:

System.out.println((minutos/60) + " horas e " + (minutos%60) + " minutos");

As suggested by @Zini , you can also format the number of decimal places using f :

    System.out.println(String.format("Distância em km c/ duas casas decimais = %.2f", (metros/1000f)));

In the example above, it will display up to two houses.

See working at ideone .

    
31.12.2016 / 12:30
0

Just to add something that was not mentioned in the other answers, you could use the (cast) coercion operator to get the result with decimal places without having to create a specific variable.

System.out.println("Distância em km = "+ (float)metros/1000);

or

System.out.println("Distância em km = "+ (double)metros/1000);

In both cases the value returned is "1.5".

    
22.02.2017 / 20:09