本文介绍了为什么javascript中的parseFloat为我返回字符串类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我搜索过,发现这个与我的问题有关,但并不完全一样,因为我使用的是固定而不是精度。
I searched and only found this one related to my question, but not exactly the same, as I'm using toFixed rather than 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
我需要进一步的数学步骤,所以字符串类型搞砸...
为什么?怎么解决? TIA
I need further math steps, so string type messed up...Why? How to solve? TIA
推荐答案
正如文档中所述,返回
As mentioned in docs, toFixed
returns
如果您需要使用返回的结果作为数字,您可以使用内置对象:
In case you need to use the returned result as a number, you can use built-in object 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中的parseFloat为我返回字符串类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!