javascript 提供了多种内置方法来有效地处理数字。这些方法允许您执行格式化、舍入、解析和验证数字等操作。
将数字转换为字符串。
const num = 123; console.log(num.tostring()); // output: "123" console.log((456).tostring()); // output: "456"
格式化具有固定小数位数的数字。
const num = 3.14159; console.log(num.tofixed(2)); // output: "3.14" console.log(num.tofixed(4)); // output: "3.1416"
返回指数表示法的数字。
const num = 12345; console.log(num.toexponential(2)); // output: "1.23e+4"
将数字格式化为指定的总长度(包括小数)。
const num = 123.456; console.log(num.toprecision(4)); // output: "123.5" console.log(num.toprecision(6)); // output: "123.456"
将字符串解析为整数。
console.log(parseint("123")); // output: 123 console.log(parseint("101", 2)); // output: 5 (binary to decimal)
将字符串解析为浮点数。
console.log(parsefloat("3.14")); // output: 3.14 console.log(parsefloat("123abc")); // output: 123
检查值是否为整数。
console.log(number.isinteger(123)); // output: true console.log(number.isinteger(3.14)); // output: false
检查一个值是否是有限数。
console.log(number.isfinite(123)); // output: true console.log(number.isfinite(infinity)); // output: false
检查值是否为 nan(非数字)。
console.log(number.isnan(nan)); // output: true console.log(number.isnan(123)); // output: false
将数字四舍五入到最接近的整数。
console.log(math.round(4.5)); // output: 5 console.log(math.round(4.4)); // output: 4
将数字向上舍入到下一个整数。
console.log(math.ceil(4.1)); // output: 5
将数字向下舍入到前一个整数。
console.log(math.floor(4.9)); // output: 4
删除数字的小数部分。
console.log(math.trunc(4.9)); // output: 4
生成 0(含)和 1(不包括)之间的随机数。
console.log(math.random()); // output: a random number between 0 and 1
生成一定范围内的随机数:
const min = 1; const max = 10; const random = math.floor(math.random() * (max - min + 1)) + min; console.log(random); // output: a random number between 1 and 10
返回数字的绝对值。
console.log(math.abs(-5)); // output: 5
返回底数的指数次方。
console.log(math.pow(2, 3)); // output: 8
返回数字的平方根。
console.log(math.sqrt(16)); // output: 4
查找一组数字中的最大值或最小值。
console.log(math.max(1, 5, 3)); // output: 5 console.log(math.min(1, 5, 3)); // output: 1
返回数字的符号(-1、0 或 1)。
console.log(Math.sign(-10)); // Output: -1 console.log(Math.sign(0)); // Output: 0 console.log(Math.sign(10)); // Output: 1
通过掌握这些数字方法,你可以轻松处理 javascript 中的各种数字运算。
嗨,我是 abhay singh kathayat!
我是一名全栈开发人员,拥有前端和后端技术方面的专业知识。我使用各种编程语言和框架来构建高效、可扩展且用户友好的应用程序。
请随时通过我的商务电子邮件与我联系:kaashshorts28@gmail.com。