javascript - 为什么 javascript 中的 parseFloat 为我返回字符串类型?

标签 javascript string types numbers parsefloat

我搜索了一下,只发现这个与我的问题相关,但并不完全相同,因为我使用的是 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/

相关文章:

go - 是否有从 ios 日志中出现的字符的术语,如 `\M-C\M-6` 或 `\134`

javascript - 如何检查 JSON 对象 ionic2 中的值

arrays - 如何在更大的数组中显示每个数组的值?

java - ClassName 为字符串时如何处理 "new Class"?

c - 将字符添加到结构体中

java - 类型与类型定义的交集

syntax - F# 前向类型声明

javascript - 批处理 Backbone.js 事件?

javascript - 函数式编程传递依赖

javascript - 使用 JQuery $(class).css() 停止 CSS webkit 动画?