Number.parseFloat()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Number.parseFloat() 静态方法解析参数并返回浮点数。如果无法从参数中解析出一个数字,则返回 NaN

尝试一下

function circumference(r) {
  if (Number.isNaN(Number.parseFloat(r))) {
    return 0;
  }
  return parseFloat(r) * 2.0 * Math.PI;
}

console.log(circumference("4.567abcdefgh"));
// Expected output: 28.695307297889173

console.log(circumference("abcdefgh"));
// Expected output: 0

语法

js
Number.parseFloat(string)

参数

string

要解析的值,会被强制转换为字符串。该参数开头的空白会被忽略。

返回值

由给定 string 解析得到的浮点数。

如果第一个非空白字符不能被转换为数字,则返回 NaN

示例

Number.parseFloat 与 parseFloat 对比

此方法与全局函数 parseFloat() 具有相同的功能:

js
Number.parseFloat === parseFloat; // true

其目的是全局的模块化。

有关更多详细信息和示例,请参见 parseFloat()

规范

Specification
ECMAScript® 2025 Language Specification
# sec-number.parsefloat

浏览器兼容性

BCD tables only load in the browser

参见