Long to Float in Java?

2

Good morning, I have the following problem I get in a variable of type Long a conversion of milliseconds to hours, but I need to store them in a Float type variable.

 tiempos.setFechaHoraFinal(fechaActual);
    tiemposFacade.edit(tiempos);
    Long diferencia = tiempos.getFechaHoraInicio().getTime() - tiempos.getFechaHoraFinal().getTime();
    long resultado = TimeUnit.MILLISECONDS.toHours(diferencia);





    tiempos.setTotalHoraHombre(diferencia.floatValue());

I need to set the variable 'result' in

 tiempos.setTotalHoraHombre(diferencia.floatValue());
    
asked by Alexander Gil Tafur 11.09.2017 в 15:28
source

1 answer

2

As @LuiggiMendozaJ says it's better to save that type of data in a more precise object (BigDecimal) by converting the difference of hours, so to your question as you convert it is to divide it among this number (3600000f) the is to explain that it is float to the compiler.

float miFloat = diferenciaEnMilisegundos/ 3600000f;

Where the number comes from is the multiplication of 1000 milliseconds that has a second, 60 seconds has a minute and 60 minutes has an hour.

More precisely, it would be the following.

BigDecimal horasHombre = new BigDecimal(diferenciaEnMilisegundos).divide(new BigDecimal(3600000), 1, RoundingMode.HALF_DOWN);

There are different types of rounding according to your convenience.

link

If you do not know well the operation of the BigDecimal class, you should give it a revised one, since in any mathematical operation (addition, subtraction, division, multiplication, etc ...) float or double will give you unexpected results due to its inaccuracy arithmetic.

    
answered by 11.09.2017 в 17:19