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.
Further reading:
Java float vs double
Let’s list down differences between float and double now,
[table id=15 /]
Let’s discuss the last point again.
So for example, if you write below code, you will get a compilation error.
float num=2.23
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.
float num=(float)2.23
or append f to the end of decimal number.
float num=2.23f
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.