掌握 JavaScript 中的数字方法

风之吻 网站开发 319

javascript 提供了多种内置方法来有效地处理数字。这些方法允许您执行格式化、舍入、解析和验证数字等操作。

掌握 JavaScript 中的数字方法-第1张图片-风享汇

1
转换数字

  a. tostring()

  将数字转换为字符串。

const num = 123;
console.log(num.tostring()); // output: "123"
console.log((456).tostring()); // output: "456"

  b.固定(数字)

  格式化具有固定小数位数的数字。

const num = 3.14159;
console.log(num.tofixed(2)); // output: "3.14"
console.log(num.tofixed(4)); // output: "3.1416"

  c.指数(数字)

  返回指数表示法的数字。

const num = 12345;
console.log(num.toexponential(2)); // output: "1.23e+4"

  d. toprecision(数字)

  将数字格式化为指定的总长度(包括小数)。

const num = 123.456;
console.log(num.toprecision(4)); // output: "123.5"
console.log(num.toprecision(6)); // output: "123.456"
2
解析和验证数字

  a. parseint(字符串, 基数)

  将字符串解析为整数。

console.log(parseint("123")); // output: 123
console.log(parseint("101", 2)); // output: 5 (binary to decimal)

  b. parsefloat(字符串)

  将字符串解析为浮点数。

console.log(parsefloat("3.14")); // output: 3.14
console.log(parsefloat("123abc")); // output: 123

  c. number.isinteger(值)

  检查值是否为整数。

console.log(number.isinteger(123)); // output: true
console.log(number.isinteger(3.14)); // output: false

  d. number.isfinite(值)

  检查一个值是否是有限数。

console.log(number.isfinite(123)); // output: true
console.log(number.isfinite(infinity)); // output: false

  e. number.isnan(值)

  检查值是否为 nan(非数字)。

console.log(number.isnan(nan)); // output: true
console.log(number.isnan(123)); // output: false
3
四舍五入数字

  a. math.round()

  将数字四舍五入到最接近的整数。

console.log(math.round(4.5)); // output: 5
console.log(math.round(4.4)); // output: 4

  b. math.ceil()

  将数字向上舍入到下一个整数。

console.log(math.ceil(4.1)); // output: 5

  c. math.floor()

  将数字向下舍入到前一个整数。

console.log(math.floor(4.9)); // output: 4

  d. math.trunc()

  删除数字的小数部分。

console.log(math.trunc(4.9)); // output: 4
4
生成随机数

  a. math.random()

  生成 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
5
其他有用的数字方法

  a. math.abs()

  返回数字的绝对值。

console.log(math.abs(-5)); // output: 5

  b. math.pow(底数, 指数)

  返回底数的指数次方。

console.log(math.pow(2, 3)); // output: 8

  c. math.sqrt()

  返回数字的平方根。

console.log(math.sqrt(16)); // output: 4

  d. math.max() 和 math.min()

  查找一组数字中的最大值或最小值。

console.log(math.max(1, 5, 3)); // output: 5
console.log(math.min(1, 5, 3)); // output: 1

  e. math.sign()

  返回数字的符号(-1、0 或 1)。

console.log(Math.sign(-10)); // Output: -1
console.log(Math.sign(0));   // Output: 0
console.log(Math.sign(10));  // Output: 1
6
总结

  javascript 提供了多种处理数字的方法,从转换到复杂的数学运算。

  math 对象包含用于高级计算的实用函数。

  使用这些方法可以有效地处理舍入、解析、格式化和生成数字。

  通过掌握这些数字方法,你可以轻松处理 javascript 中的各种数字运算。

标签: JS

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~