Floating Data Type – Basic to Advanced
The Floating Data Type is used to store decimal numbers. It is one of the most important data types used in real-world applications such as scientific calculations, measurements, financial estimates, engineering, and more. This guide explains everything from basic definition to advanced internal working with clean examples.
What is a Floating Data Type?
A Floating (Float) Data Type is used to store decimal numbers. Numbers that contain a decimal point are called floating numbers. Examples:
- 3.14
- 10.5
- -0.98
- 5.0
It stores fractional values and can handle both small and very large decimal numbers.
Why is it called “Floating”?
It is called Floating because the decimal point is not fixed—it “floats” based on the number size. Example:
- 3.1415
- 314.15
- 0.00031415
In all cases, the decimal shifts position dynamically.
Size and Range of Float
Float generally uses 4 bytes of memory.
Its approximate range is: ±3.4 × 10⁻³⁸ to ±3.4 × 10³⁸
Float Precision (Accuracy)
Float provides around 6 to 7 digits of precision.
Example: If you store 3.14159265 in a float, it will store approx 3.141593.
Internal Structure of Float (Advanced)
A float is stored in 3 major parts:
- Sign Bit – Tells if number is positive or negative
- Exponent – Tells where the decimal point is placed
- Mantissa (Fraction) – Stores the actual value
This is known as Floating Point Representation.
Float vs Integer Comparison
| Feature | Integer | Float |
|---|---|---|
| Meaning | Whole numbers | Decimal numbers |
| Precision | Exact | Approx (6–7 digits) |
| Speed | Fast | Slightly slower |
| Use Case | Counting, age, quantity | Measurements, price, temperature |
Advantages of Float
- Supports decimal numbers
- Uses less memory
- Faster in calculations
- Useful in scientific and engineering data
Disadvantages of Float
- Limited precision
- Rounding errors occur
- Not suitable for money calculations
JavaScript Example Programs
1. Basic Float Example
let price = 99.75; console.log(price);
2. Float Addition
let a = 5.5; let b = 2.3; console.log(a + b);
3. Float Multiplication
let result = 4.5 * 2.0; console.log(result);
4. Rounding a Float
let num = 3.141592; console.log(num.toFixed(3));
5. Rounding Error Example
let x = 0.1 + 0.2; console.log(x);
Final Summary
A Float is used to store decimal numbers. It occupies 4 bytes and provides 6–7 digits of precision. It is perfect for real-world measurements but suffers from rounding errors due to binary representation.
Comments
Post a Comment