Java float vs double

Previous
Next

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,

Parameter float double
Memory 4 bytes 8 bytes
Precision A float can give you approx 6-7 decinal points precision double can give you approx. 15-16 decimal points precision
Range float hs range from 1 .7e–308 to 1.7e+308 double has range from 3 .4e–038 to 3.4e+038
default float is not used by default By 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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog