数字 and Math
学习如何数字工作 in code: integers, floats, arithmetic 运算符, rounding, and Math 对象.
你将学到
- 如何数字是 represented in JavaScript (integers and floats)
- Arithmetic 运算符 and 运算符 precedence
- Math 对象: rounding, powers, random, 最小值/最大值
- 常见 pitfalls 使用 floating-点 precision
- 如何 convert 字符串到 数字 safely
概念讲解
Numbers and Math
Numbers are the other fundamental data type alongside strings. JavaScript has a single numeric type called Number that represents both integers (42) and decimals (3.14). Understanding how numbers behave — especially their limitations — prevents a whole class of subtle bugs.
Arithmetic Operators
The basic operators are + (add), - (subtract), * (multiply), / (divide), and % (modulo — the remainder). There are also compound assignment operators like +=, -=, *=, and /= that combine an operation with assignment:
let total = 10;
total += 5; // total is now 15 (same as total = total + 5)
total *= 2; // total is now 30
const remainder = 17 % 5; // 2 (17 divided by 5 leaves remainder 2)
Operator Precedence
Operators follow precedence rules — the same rules you learned in math class. Multiplication and division happen before addition and subtraction. Use parentheses to override the default order and to make your intent explicit:
const a = 2 + 3 * 4; // 14 (multiplication first)
const b = (2 + 3) * 4; // 20 (parentheses override)
The Math Object
JavaScript provides a built-in Math object with useful functions:
Math.round(x)— round to the nearest integer.Math.floor(x)— round down.Math.ceil(x)— round up.Math.最大值(, b, c)/Math.最小值(, b, c)— largest or smallest value.Math.random()— a random decimal between 0 (inclusive) and 1 (exclusive).Math.pow(基础, exp)— exponentiation. Also written as基础 ** exp.
Floating-Point Precision
Computers store numbers in binary, and some decimal fractions cannot be represented exactly. This leads to surprising results:
0.1 + 0.2; // 0.30000000000000004 (not exactly 0.3!)
This is not a JavaScript bug — it happens in nearly every language. For money or other precision-critical values, multiply by 100 and work in cents (integers), or use a dedicated decimal library.
Converting Strings to Numbers
Use 数字(), parseInt(), or parseFloat() to convert text to a number. Always validate the result with 数字.isNaN() before using it, because invalid input produces NaN (Not-a-Number), which silently propagates through calculations.
示例代码
// Calculate a shopping cart total with tax
const prices = [12.99, 5.49, 3.00, 8.75];
const taxRate = 0.08;
let subtotal = 0;
for (const price of prices) {
subtotal += price;
}
const tax = subtotal * taxRate;
const total = subtotal + tax;
// Round to 2 decimal places for display
const displayTotal = Math.round(total * 100) / 100;
console.log(`Subtotal: $${subtotal.toFixed(2)}`);
console.log(`Tax: $${tax.toFixed(2)}`);
console.log(`Total: $${displayTotal}`);
// Generate a random integer between 1 and 100
const random = Math.floor(Math.random() * 100) + 1;
console.log("Random number:", random);
这个示例总和 prices, calculates tax, and rounds result. toFixed(2) 格式数字 as 字符串使用精确地 2 decimal 位置 — useful for currency display.
动手试一试
- 数字基础 Converter
Convert 数字之间 binary, octal, decimal, and hexadecimal — see 如何相同值 是 represented in 不同基础.
- Math 表达式 Evaluator
Evaluate arithmetic 表达式使用 proper 运算符 precedence. 类型 formulas and see 如何 precedence 规则 apply.
常见错误
错误写法
Trusting floating-点 arithmetic for money calculations.
正确做法
工作 in integer cents (multiply 通过 100) or use decimal 库. 从不存储 currency as floating-点 dollars — rounding 错误将 accumulate.
错误写法
Forgetting 那个 parseInt 停止 at 首先非-digit character.
正确做法
parseInt('42px') 返回 42, 哪个可能 hide 无效输入. 总是验证使用数字.isNaN 之后 conversion, or use 数字() 哪个返回 NaN for 无效字符串.
错误写法
Using == 到 compare 数字那个可能是 字符串.
正确做法
Use === (strict equality). '5' == 5 是真 (coercion), 但 '5' === 5 是假. Explicit conversion 使用数字() 是 safer than relying on coercion.
相关资源
相关速查表
- JavaScript Cheatsheet
引用 for 所有 Math 方法, arithmetic 运算符, and 数字 conversion 函数.
练习 数字 and Math
11 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。