为什么javascript中的parseFloat为我返回字符串类型? [英] Why parseFloat in javascript returns string type for me?

查看:346
本文介绍了为什么javascript中的parseFloat为我返回字符串类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索过,发现这个与我的问题有关,但并不完全一样,因为我使用的是固定而不是精度。
为什么toPrecision会返回字符串?

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

推荐答案

正如文档中所述, toFixed 返回

As mentioned in docs, toFixed returns


使用定点表示法表示给定数字的字符串

A string representing the given number using fixed-point notation

如果您需要使用返回的结果作为数字,您可以使用内置对象 数字

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为我返回字符串类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆