我搜索了一下,只发现这个与我的问题相关,但并不完全相同,因为我使用的是 toFixed 而不是 toPrecision。 Why does toPrecision return a String?
这是我的代码
var oldv = parseFloat(document.getElementById('total').textContent).toFixed(2);
alert(typeof oldv); // returns string
var testv = parseInt(document.getElementById('total').textContent);
alert(typeof testv); // returns number
我需要进一步的数学步骤,所以字符串类型搞砸了... 为什么?怎么解决?时间差
最佳答案
如文档中所述,toFixed
返回
A string representing the given number using fixed-point notation
如果您需要将返回的结果用作数字,您可以使用内置对象 Number
:
var oldv = parseFloat(Math.PI).toFixed(2);
console.log( oldv );
console.log( typeof oldv ); // returns string
var num = Number(oldv);
console.log( num );
console.log( typeof num ); // returns number
关于javascript - 为什么 javascript 中的 parseFloat 为我返回字符串类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46757305/