Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is float in JavaScript

Understanding Floats in JavaScript

Floats: What are they?

In JavaScript, a float (more formally known as a floating-point number) is a type of data that allows you to store decimal numbers. This is in contrast to integers, which can only store whole numbers. If you think about numbers on a number line, an integer would only be able to represent the ticks on the line (like -1, 0, 1, 2, 3, etc.), while a float could represent any number on the line.

For example, the number 7.89 is a floating-point number. Similarly, numbers like 0.0001 and -123.45 are also floating-point numbers.

Creating Floats

In JavaScript, you can create a floating-point number just by typing the number out in your code, like so:

let myNumber = 7.89;

In the above example, myNumber is a variable that holds the floating-point number 7.89.

Operations with Floats

You can perform all the usual mathematical operations with floats. This includes addition, subtraction, multiplication, and division. Here is an example:

let a = 5.2;
let b = 3.8;
let sum = a + b; // results in 9
let difference = a - b; // results in 1.4
let product = a * b; // results in 19.76
let quotient = a / b; // results in 1.368421052631579

Floats and Precision

One thing to be aware of when working with floating-point numbers in JavaScript is that they are not always 100% precise. Due to the way that JavaScript (and many other programming languages) store floating-point numbers, you can sometimes get unexpected results.

For example, try running this code:

let result = 0.1 + 0.2;
console.log(result);  

Instead of getting the expected result of 0.3, you will see that the actual result is something like 0.30000000000000004. This is a tiny error, and for many purposes, it doesn't really matter. But if you're writing a program where precise calculations are important, it's something to be aware of.

Floats In Comparison

Another thing to keep in mind is when using floating-point numbers in comparison operations. Let's consider an example:

let a = 0.1 + 0.2;
let b = 0.3;

console.log(a === b); // false

Even though 0.1 + 0.2 is mathematically equal to 0.3, in JavaScript, a === b returns false. This is because of the same precision issues we talked about above.

Conclusion

To understand float in JavaScript is to unlock a whole new level of numerical operations and precision in your coding journey. It's like having a Swiss Army knife in your toolbox; it might not be the tool you use every day, but when you need it, it's invaluable. So take your time, practice with various numbers and operations, and soon, working with floats will become second nature. Remember, every expert was once a beginner who refused to give up. Happy coding!