Skip to content
← Back to rules

unicorn/prefer-number-coercion Pedantic

💡 A suggestion is available for this rule.

作用

优先使用 Number(),而不是 parseFloat() 和以 10 为基数的 parseInt()

为什么这不好?

parseFloat()parseInt() 会解析数字前缀并忽略后面的文本。 Number() 会解析完整输入,在进行值转换时更符合预期。

示例

以下是此规则的错误代码示例:

javascript
const value = parseFloat(input);
const integer = parseInt(input, 10);

以下是此规则的正确代码示例:

javascript
const value = Number(input);
const integer = Math.trunc(Number(input));

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "unicorn/prefer-number-coercion": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/prefer-number-coercion": "error",
  },
});
bash
oxlint --deny unicorn/prefer-number-coercion

版本

此规则于 v1.71.0 中添加。

参考文献