JavaScript Numbers
In JavaScript, numbers are always stored as floating-point values (even integers). Unlike other languages, there’s no separate type for int
and float
. Let’s dive into how JavaScript handles numbers and their built-in methods!
1️⃣ Declaring Numbers
📌 JavaScript automatically converts between integer and floating-point values.
2️⃣ Number Methods
🔹 toFixed(n)
– Rounds to n
decimal places (returns a string)
🔹 toPrecision(n)
– Formats number to n
significant digits
🔹 toString(base)
– Converts number to a string in a given base
🔹 Number.isInteger(value)
– Checks if a number is an integer
🔹 Number.isNaN(value)
– Checks if a value is NaN
3️⃣ Special Number Values
🔹 Infinity
& -Infinity
🔹 NaN
(Not a Number)
Occurs when an invalid mathematical operation is performed.
📌 NaN
is the only value that is not equal to itself:
Use Number.isNaN(value)
instead of value === NaN
.
4️⃣ Math Object – Useful Methods
The Math
object provides built-in functions for mathematical operations.
🔹 Math.round()
– Rounds to nearest integer
🔹 Math.floor()
– Rounds down
🔹 Math.ceil()
– Rounds up
🔹 Math.trunc()
– Removes decimal part
🔹 Math.random()
– Generates a random number between 0 and 1
To get a random integer in a range:
🔹 Math.pow(base, exponent)
– Power function
🔹 Math.sqrt(n)
– Square root
🔹 Math.abs(n)
– Absolute value
🔹 Math.max()
& Math.min()
5️⃣ Converting Strings to Numbers
🔹 Number(value)
– Converts string to number
🔹 parseInt(value, base)
– Converts string to integer
🔹 parseFloat(value)
– Converts string to floating-point number
📌 parseInt()
and parseFloat()
ignore non-numeric characters after a valid number, while Number()
returns NaN
if the input contains non-numeric characters.
6️⃣ Handling Precision Issues
JavaScript has floating-point precision issues:
🔹 Fix using toFixed()
7️⃣ Checking for Finite Numbers
🔹 Number.isFinite(value)
Checks if a value is a finite number (not NaN
, Infinity
, or -Infinity
).
8️⃣ Summary
✔ All numbers in JavaScript are floating-point
✔ Use toFixed()
and toPrecision()
to format numbers
✔ Use Math
functions for advanced calculations
✔ Use Number()
, parseInt()
, and parseFloat()
for conversions
✔ Be mindful of floating-point precision issues
🚀 Now you're a pro at handling numbers in JavaScript! Let me know if you need more examples. 😊