Java float vs double

In this post, we will see the difference between float and double data types in java.

As you might know, float and double both can be used to represent floating point number in java. We will see the difference between float and double and also when to use double vs float.

Similarities between double and float

  • double and float both can represent decimal numbers in java.
  • double and float both are not precise. They have approximate values.

Java float vs double

Let’s list down differences between float and double now,

Parameterfloatdouble
Memory4 bytes8 bytes
PrecisionA float can give you approx 6-7 decinal points precisiondouble can give you approx. 15-16 decimal points precision
Rangefloat hs range from 1 .7e–308 to 1.7e+308double has range from 3 .4e–038 to 3.4e+038
defaultfloat is not used by defaultBy default, Java uses double to represent its floating-point numerals

Let’s discuss the last point again.
So for example, if you write below code, you will get a compilation error.

Reason is java consider decimal number as double by default.If you want to use it as float then there are two option,

You cast the number to float.

or append f to the end of decimal number.


When to use float and double

If your program has memory constraints and you know that number will fit in float range then go for float. In all other cases, you should use double for decimal points.

That’s all about Java float vs double.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *