JavaScript: JavaScript Numbers and Math

Last updated: 2026-10-13

In JavaScript, there is only one number type: Number. Whether it's an integer or a decimal, it's all Number. This is different from languages like Java or C that distinguish between int, float, and so on. Simpler, yes — but it comes with a few gotchas.

Related Math Methods:Number.isNaN() Math.random() Math.floor() Math.round() Math.ceil() Math.abs() Math.max() Math.min() Math.pow() isFinite() toFixed() Number() parseInt Math

1. Number Type

In JavaScript, both integers and floating-point numbers are the Number type — there is no separate integer type.

HTML
<script>
let a = 42;        // This is a Number
let b = 3.14;      // This is also a Number
typeof a;          // "number"
typeof b;          // "number"
</script>

Numbers can also be written in several other formats:

HTML
<script>
let hex = 0xFF;       // Hexadecimal, equals 255
let octal = 0o10;     // Octal, equals 8
let binary = 0b1010;  // Binary, equals 10
let big = 1e6;        // Scientific notation, equals 1000000
</script>

2. NaN and Infinity

NaN stands for "Not a Number," yet it is of type Number — one of JavaScript's most ironic design choices.

HTML
<script>
typeof NaN;          // "number"  ← That's right, it's actually a number
NaN === NaN;         // false     ← It's not even equal to itself!
Number.isNaN(NaN);   // true      ← Use this method to check for NaN
</script>

When does NaN appear? When you try to do math with something that isn't a number:

HTML
<script>
parseInt('abc');    // NaN
'hello' * 5;       // NaN
Math.sqrt(-1);     // NaN
</script>

Infinity represents positive infinity and appears when dividing by zero:

HTML
<script>
1 / 0;             // Infinity
-1 / 0;            // -Infinity
typeof Infinity;   // "number"
</script>
💡 Tip: To check if a value is NaN, never use === — use Number.isNaN(). Since NaN === NaN is false, this is a trap that has caught countless developers.


3. Floating-Point Precision

This is JavaScript's most famous quirk: 0.1 + 0.2 !== 0.3.

HTML
<script>
0.1 + 0.2;          // 0.30000000000000004
0.1 + 0.2 === 0.3;  // false
</script>

The reason is related to how computers store floating-point numbers in binary. The value 0.1 is a repeating fraction in binary, leading to precision loss during storage. This isn't unique to JavaScript — all languages using the IEEE 754 standard have this issue.

The fix: use toFixed() for formatting, or scale up before computing:

HTML
<script>
(0.1 + 0.2).toFixed(2);   // "0.30"
(0.1 * 100 + 0.2 * 100) / 100;  // 0.3
</script>

▶ Example: Precision Issues Demo

▶ Try it Yourself

4. The Math Object

Math is JavaScript's built-in math utility. No instantiation needed — just call its methods directly:

Method/Property Purpose Example
Math.round() Round to nearest integer Math.round(4.6) → 5
Math.floor() Round down Math.floor(4.9) → 4
Math.ceil() Round up Math.ceil(4.1) → 5
Math.random() Random number 0–1 Math.random() → 0.3721...
Math.max() Maximum value Math.max(1,5,3) → 5
Math.min() Minimum value Math.min(1,5,3) → 1
Math.PI Pi 3.141592653589793
Math.abs() Absolute value Math.abs(-7) → 7
Math.pow() Exponentiation Math.pow(2,3) → 8
Math.sqrt() Square root Math.sqrt(16) → 4

▶ Example: Common Math Methods

▶ Try it Yourself
💡 Tip: Math.round(-1.5) returns -1, not -2. Rounding behavior at the negative boundary may not match your intuition — keep this in mind.


5. toFixed() — Formatting Decimals

toFixed(n) formats a number to n decimal places and returns a string:

HTML
<script>
let price = 9.9;
price.toFixed(2);    // "9.90"  ← Note: returns a string
+(9.9).toFixed(2);   // 9.9     ← Use + to convert back to a number
</script>
⚠️ Note: toFixed returns a string! If you need to do further math with it, remember to convert it back to a number.


6. toString() — Base Conversion

The number method toString(radix) converts a number to a string in the specified base:

HTML
<script>
(255).toString(16);   // "ff"  hexadecimal
(255).toString(2);    // "11111111"  binary
(255).toString(8);    // "377"  octal
(100).toString();     // "100"  decimal (default)
</script>

▶ Example: Base Conversion

▶ Try it Yourself

7. Math.random() — Generating Random Numbers

Math.random() returns a random floating-point number between 0 (inclusive) and 1 (exclusive). In practice, you often need a random integer within a specific range:

HTML
<script>
// Generate a random integer between min and max (inclusive)
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>

▶ Example: Random Number Demo

▶ Try it Yourself
💡 Tip: Math.random() produces pseudo-random numbers and is not suitable for cryptographic purposes. For cryptographically secure randomness, use crypto.getRandomValues().


Related Math Methods:Number.isNaN() Math.random() Math.floor() Math.round() Math.ceil() Math.abs() Math.max() Math.min() Math.pow() isFinite() toFixed() Number() parseInt Math

❓ FAQ

Q What are Math.round(2.5) and Math.round(-2.5) respectively?
A Math.round(2.5) is 3, and Math.round(-2.5) is -2. When the decimal is exactly .5, JavaScript rounds toward positive infinity — so both positive and negative numbers round up (closer to 0).
Q How do I check if a value is a valid, finite number?
A Use Number.isFinite(value). It excludes NaN, Infinity, and -Infinity, and also rejects non-number types. The global isFinite() works too but doesn't check the type (it coerces first).
Q What's the difference between parseInt and Number()?
A parseInt('12abc') returns 12 — it parses left to right until it can't continue. Number('12abc') returns NaN — the entire string must be a valid number. Use parseInt for lenient parsing and Number() for strict conversion.

📖 Summary

📝 Exercises

  1. Write a program that takes a circle's radius as input, calculates its area and circumference, and displays the results rounded to 2 decimal places.
  2. Write a number guessing game: the program randomly generates an integer between 1 and 100, the user enters guesses, and the program responds with "Too high" or "Too low" until the correct answer is found.
  3. Write a base converter: input a decimal number and simultaneously display its binary, octal, and hexadecimal equivalents.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏