Format result of integer division

Asked

Viewed 1,174 times

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 possible.

This same problem applies to hours, for example when asked to split 90 min he should return to me 1 and 30 min of the surplus, instead returns me 1 hour.

  • No converting is no way, 1.5 is a float, if at least one of the operands is not a float or double, its division will never have decimal places, not making use of integer splitting.

  • There are two different problems, it would be interesting to present the part of the code of the second problem too.

  • @diegofm thanks! By the look I will have to create a variable... But as for the formatting of time, I have how to do this?

  • 1

    Do not have to create variable, just have to convert.

  • 1

    A simple solution would be: System.out.println((minutos/60) + " horas e " + (minutos%60) + " minutos");

  • I believe that the idea of formatting km is similar to the one above. Of course you can use Formatter for better display as well.

  • Thanks, I’ll apply to my problem

Show 2 more comments

2 answers

9


A straightforward and simple solution would simply add a f float in one of the operands:

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

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

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

At the suggestion of @Zini, you can also format the number of decimals using printf:

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

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

See working on ideone.

  • Use this to control the number of houses in the division: System.out.println(String.format("Distance in km = %.2f", (3/1000f)));

  • 1

    @Zini thanks :) updated in reply.

0

Just to add something that was not mentioned in the other answers, you could use the unary coercion operator (cast) to get the result with decimals without creating 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".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.