JavaScript 数值类型操作技巧

本笔记详细整理了 JavaScript 中对数值类型的操作技巧,包括取整、格式化、输入限制和生成随机数的方法。


1. 数值取整

方式一:使用 ~~ 双按位取反

特点

  • 将小数直接截取为整数(取整)。
  • 只支持 32 位以内的整数,超过范围会返回错误结果。
  • 遇到非数值时返回 0

代码示例

var num = "01";
console.log(~~num); // 输出: 1
 
console.log(~~2147483648.1); // 输出: -2147483648
console.log(~~"1111aa");     // 输出: 0
console.log(~~"1111.999");   // 输出: 1111
console.log(~~"-1111.999");  // 输出: -1111

原理

  • 单个 ~ 是按位取反操作符。
  • ~~ 实际上是两次按位取反,效果是快速取整。
  • 等价于 Number() 转换,但更简洁。

方式二:使用按位或 | 操作

代码示例

console.log(23.4 | 0);  // 输出: 23
console.log(-19.6 | 0); // 输出: -19

特点

  • ~~ 类似,直接取整。
  • 同样只支持 32 位整数。

2. 限制输入框只能输入正整数

实现方式一:通过数值转换

代码示例

function toInt(number) {
    return Infinity === number ? 0 : (number * 1 || 0).toFixed(0) * 1;
}
 
console.log(toInt(1));         // 输出: 1
console.log(toInt("0001"));    // 输出: 1
console.log(toInt(Infinity));  // 输出: 0

实现方式二:通过正则表达式

代码示例

function toInt2(value) {
    return `${value}`.replace(/[^\d]/g, ""); // 去除非数字字符
}
 
console.log(toInt2("abc123"));  // 输出: "123"
console.log(toInt2("-00123"));  // 输出: "00123"

实现方式三:综合使用

代码示例

function toInt3(value) {
    const strValue = `${value}`.replace(/[^\d]/g, ""); // 去掉非数字字符
    return Infinity === +strValue ? 0 : (+strValue || 0);
}
 
console.log(toInt3("abc00123")); // 输出: 123
console.log(toInt3("-Infinity")); // 输出: 0

3. 格式化数值

保留两位小数

代码示例

const NumericalProcessing = (val) => {
    let num = +val;
    if (isNaN(num)) num = 0; // 非数字返回 0
    num = (Math.round(num * 10000) / 10000.0).toFixed(2);
    return num;
};
 
console.log(NumericalProcessing(100));      // 输出: "100.00"
console.log(NumericalProcessing("123.456")); // 输出: "123.46"

特点

  • 使用 Math.round 进行四舍五入。
  • 结果统一为字符串形式,可避免浮点数误差。

4. 生成随机数

1 到 x 之间的随机整数

代码示例

function getRandomInt(x) {
    return Math.ceil(Math.random() * x);
}
 
console.log(getRandomInt(10)); // 输出: 随机整数(1~10)

原理

  • Math.random() 返回 01 的随机小数。
  • 乘以 x 后,通过 Math.ceil() 向上取整,确保范围为 1 ~ x

总结

操作方法适用场景
取整~~num / `num0`
输入限制为正整数正则 + 数值转换限制用户输入内容,只允许正整数
保留两位小数Math.round + toFixed格式化数值,解决浮点数精度问题
生成随机数Math.ceil(Math.random())随机整数生成,范围可自定义(1 ~ x)

这份笔记涵盖了常用数值操作的详细实现和应用场景,便于日常开发中快速参考和应用!