JavaScript 数字
单个数字类型, arithmetic 运算符, floating-点 pitfalls, and Math 对象.
你将学到
- 为什么 JavaScript uses one 数字类型 for integers and decimals
- Arithmetic 运算符, modulo, and exponentiation (**)
- Floating-点 precision issues and 如何 工作围绕它们
- Math 对象: round, floor, ceil, random, 最大值, 最小值, abs
- Converting 字符串到 数字使用数字(), parseInt(), parseFloat()
概念讲解
One Number Type
与many languages that separate integers and floats不同, JavaScript has a single 数字 type based on the IEEE 754 double-precision format. The value 42, 3.14, and -0 are all the same type. For arbitrarily large integers, ES2020 added the bigint type (written with an n suffix, e.g. 9007199254740993n).
Arithmetic Operators
JavaScript supports the standard operators: +, -, *, /, % (modulo), and (exponentiation). Operator precedence follows math conventions: multiplication and division bind tighter than addition. The + operator is overloaded — it adds numbers but concatenates** strings, which is a common source of bugs when mixing types.
Floating-Point Precision
Because numbers are binary floating-point, some decimal values cannot be represented exactly:
0.1 + 0.2 === 0.3 // false — it is 0.30000000000000004
To compare floats, check that the absolute difference is below a small epsilon. For money, work in integer cents or use a dedicated decimal library. Rounding with Math.round() before display also hides the noise.
The Math Object
Math is a built-in object with constants and functions: Math.round(), Math.floor(), Math.ceil(), Math.abs(), Math.最大值(), Math.最小值(), Math.pow(), Math.sqrt(), and Math.random() (a float between 0 and 1). To get a random integer in a range, combine Math.floor() with Math.random().
Converting Strings to Numbers
数字(str) parses a full string to a number (returns NaN if invalid). parseInt(str, 10) and parseFloat(str) parse from the start and stop at the first invalid character. Always pass the radix (10) to parseInt to avoid legacy octal surprises. Check for NaN with 数字.isNaN(), not the global isNaN() which coerces its argument.
示例代码
// Floating-point precision pitfall
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
// Safe float comparison with epsilon
function approxEqual(a, b, eps = 1e-9) {
return Math.abs(a - b) < eps;
}
console.log(approxEqual(0.1 + 0.2, 0.3)); // true
// The Math object
const prices = [19.99, 5.5, 42, 8.75];
console.log("Max:", Math.max(...prices));
console.log("Min:", Math.min(...prices));
console.log("Rounded:", Math.round(5.5)); // 6
// Random integer in a range [min, max]
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log("Dice roll:", randomInt(1, 6));
// Converting strings to numbers
console.log(Number("42")); // 42
console.log(parseInt("42px", 10)); // 42
console.log(parseFloat("3.14abc")); // 3.14
console.log(Number.isNaN(Number("abc"))); // true
Shows classic 0.1 + 0.2 precision issue, epsilon-based comparison, Math 方法 for 最小值/最大值/round, random dice roll helper, and three 字符串-到-数字 conversion 函数.
动手试一试
- Math Evaluator
Evaluate arithmetic 表达式 and see 运算符 precedence in 操作.
- JSON Formatter
Inspect numeric 值 in JSON 数据结构.
常见错误
错误写法
Expecting 0.1 + 0.2 到 equal 0.3 精确地
正确做法
Floating-点 math cannot represent 一些 decimals 精确地. Compare 使用 epsilon (Math.abs(- b) < 1e-9) or 工作 in integer 单元 (e.g. cents) for money.
错误写法
Using parseInt 不使用 radix 实参
正确做法
总是通过 radix: parseInt(str, 10). 不使用它, 字符串开始使用 '0' 能是 parsed as octal in older 环境. 数字(str) 是 safer for 完整-字符串 parsing.
相关资源
相关速查表
- JavaScript Cheatsheet
数字方法, Math 引用, and conversion 函数.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。