- Float data type in java is represented in 32 bits, with 1 sign bit, 8 bits of exponent, and 23 bits of the mantissa
- Where as Double is is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of mantissa.
- Default value of float is 0.0f.
- Default value of double is 0.0d.
- Floating points numbers also known as real numbers and in java there are two types of floating point one is float and another one is double.
In Java, both double ;and float are used for storing decimal numbers, but they are not the same in the following ways:
float | double | |
---|---|---|
Size | 32-bit (4 bytes) | 64-bit (8 bytes) |
Precision | ~6-7 decimal digits | ~15-16 decimal digits |
Default Type | No (needs f or F) | Yes (default for decimals) |
Performance | Faster on some processors | Higher precision, may be slower |
Range | ±3.4 × 10³⁸ | ±1.8 × 10³⁰⁸ |
Usage | When memory is a concern | When high precision is needed |
When to Use:
- Use float when dealing with graphics or in game development when memory savings are more significant than precision.
- Use double for scientific calculations, financial applications, or whenever high precision is critical.
- Float specifies single precision and double specifies double precision.
- According to the IEEE standards, float is a 32 bit representation of a real number while double is a 64 bit representation
- Normally we use double instead of float to avoid common overflow of range of numbers
- Check below diagram for width and range of float and double data types
When do you use float and when do you use double:
- Use double data type for all your calculations and temp variables.
- Use float when you need to maintain an array of numbers - float[] array (if precision is sufficient), and you are dealing with over tens of thousands of float numbers.
- Most of the math functions or operators convert/return double, and you don't want to cast the numbers back to float for any intermediate steps.
How many significant digits have floats and doubles in java?
- In java float can handle about 7 decimal places.
- And double can handle about 16 decimal places
Program #1: write a java example program which explains differences between float and double in java
- package com.instanceofjava.floatvsdouble;
- import java.math.BigDecimal;
- public class FloatVsDouble {
- /**
- * @website: www.instanceofjava.com
- * @category: float vs double in java with example program
- */
- public static void main(String[] args) {
- float a=10.8632667283322234f;
- double b=10.8632667283322234f;
- System.out.println("float value="+a);
- System.out.println("double value="+b);
- b=10.8632667283322234d;
- System.out.println("float value="+a);
- System.out.println("double value="+b);
- }
- }
Output:
- float value=10.863267
- double value=10.863266944885254
- float value=10.863267
- double value=10.863266728332224
No comments