Daniel Viaño Daniel Viaño - 3 months ago 7x
Android Question

Can I mix float, long, double values when operating in Java?

I'm getting some values from different functions, some floats, other doubles, long...

I need to operate with them.

Is it correct to do it without previously converting to the same kind of number?

For example:

float distanceInMetersFloat = initialPosition.distanceTo(finalPosition);
long deltaTimeNanosLong = (finalPosition.getElapsedRealtimeNanos() - initialPosition.getElapsedRealtimeNanos()); // nanoseconds
long deltaTimeSecondsLong = deltaTimeNanosLong / 1000000000;

double speed = distanceInMetersFloat / deltaTimeNanosLong;

I have much more precision than I need, it doesn't matter to me to lose some decimal numbers.


Be clear that you are mixing 32-bit values and 64-bit numbers. So you need to work towards ending up with the bigger 64-bit results t avoid losing data.

And be aware that you are mixing integer numbers with fractional numbers.

On both issues above, study carefully how Java primitives syntax works with numeric literals.


  • Append an L to long literals.
  • Append f to float literals. And d to double literals.
  • Use underscores to group your digits for easier reading. Ex: 1_000_000

Lastly, be aware that float and double are both floating-point numbers. Floating-point technology trades off accuracy for performance. This is good for rendering curves in a drawing or rendering a game, but bad for money or other values where you don't want extraneous extra digits in your decimal fraction.


If accuracy matters, I would convert all your values to BigDecimal objects rather than primitives. BigDecimal eschews floating-point. Much slower, but accurate.