javascript - .toFixed() 调用负指数返回一个数字,而不是一个字符串

标签 javascript node.js tofixed

我注意到当针对负指数调用 toFixed 时,结果是一个数字,而不是一个字符串。

首先,让我们看一下规范。

Number.prototype.toFixed (fractionDigits)

Return a String containing this Number value represented in decimal fixed-point notation with fractionDigits digits after the decimal point. If fractionDigits is undefined, 0 is assumed.

实际发生的是(在 Chrome、Firefox、Node.js 中测试):

> -3e5.toFixed()
-300000

因此,返回值为-3e5。另外,请注意这不是字符串。这是一个数字:

> x = -3e5.toFixed()
-300000
> typeof x
'number'

如果我将输入括在括号中,它会按预期工作:

> x = (-3e5).toFixed()
'-300000'
> typeof x
'string'

为什么会这样?什么解释?

最佳答案

我猜这是因为与符号运算符相比,成员 ('.') 运算符的优先级更高。

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

关于javascript - .toFixed() 调用负指数返回一个数字,而不是一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722066/

相关文章:

javascript - 当我们点击某些文本时如何制作弹出屏幕

javascript - MongoDB - MongoError : connect ECONNREFUSED

node.js - 无法读取未定义的属性 'getPayload'

javascript - 将乘法金额结果限制为小数点后 2 位

javascript - 函数会输出 nan 而不是数字,为什么?

javascript - 在 Javascript 中,toFixed() 是否对货币足够准确?

javascript - 如何使用 jQuery 加载包含 Chart.js 的页面

javascript - 如何在同一域但不同协议(protocol)(http 与 https)上共享 localStorage

javascript - 对象窗口 ['0' ] 和窗口 ['1' ] 在 javascript 中的含义是什么

node.js - 如何使用 nodejs 创建可下载的 zip 文件?